VB.NET TcpListener 表单未显示

VB.NET TcpListener FORM NOT SHOWING

我正在使用上面的代码 运行 带有 tcplistener 的表单。

当 tcplistener 从客户端接收数据时,我需要将数据写入 label1.text

我尝试使用 Shown 而不是 Load 来显示表单,但标签文本没有改变。

我该如何解决这个问题?任何帮助将不胜感激。

谢谢

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) 句柄 MyBase.Load

TcpServer()

结束子

Shared Sub TcpServer()

    Dim server As TcpListener
    server = Nothing
    Try

        Dim port As Int32 = 4000
        Dim localAddr As IPAddress = IPAddress.IPv6Any 'IPAddress.Parse("192.168.61.9") 'IPAddress.Any 
        server = New TcpListener(localAddr, port)
        server.Start()

        Dim bytes(1024) As Byte
        Dim data As String = Nothing

        While True
            Console.WriteLine("Waiting for a connection... ")

            Dim client As TcpClient = server.AcceptTcpClient()
            Console.WriteLine("Connected!")

            data = Nothing

            Dim stream As NetworkStream = client.GetStream()

            Dim i As Int32

            ' Loop to receive all the data sent by the client.
            i = stream.Read(bytes, 0, bytes.Length)
            While (i <> 0)
                ' Translate data bytes to a ASCII string.
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
                Form1.Label1.Text = data

                ' Process the data sent by the client.
                'data = data.ToUpper()
                data = "aaa"
                Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)

                ' Send back a response.
                stream.Write(msg, 0, msg.Length)
                Console.WriteLine("Sent: {0}" + data)

                i = stream.Read(bytes, 0, bytes.Length)

            End While

            ' Shutdown and end connection
            client.Close()
            Form1.Refresh()
        End While
    Catch e As SocketException
        MsgBox("SocketException: {0}", e.ToString)
    Finally
        server.Stop()
    End Try

    Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
    Console.Read()
End Sub 'Main

运行 新线程上的 TcpServer(),或使用作为 winForms 控件一部分的 BackGroundWorker 控件。