各位老大,小弟初学VB,请多赐教:
环境:visual studio 2015, Visual Basic
参考程序:https://msdn.microsoft.com/zh-cn/library/system.net.sockets.tcplistener.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
改造:把原来程序里边的try catch去掉了,程序由一个按钮控制启动
运行情况:程序基本成功,能够正确接受来自client端的请求并做出相应
问题:程序进入while语句后,其他什么事情都做不了,一门心思地在等待客户端的请求;甚至于我在程序界面做了一个退出按钮想退出程序也不行。
希望:程序在监听客户端请求的时候,也可以允许我做一些其它事情,必须在界面上做一些其它输入操作,允许我按界面上的按钮。非常感谢各位大侠!主程序如下:
        Dim server As TcpListener
        server = Nothing        ' Set the TcpListener on port 13000.
        Dim port As Int32 = 13000
        Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")
        server = New TcpListener(localAddr, port)        ' Start listening for client requests.
        server.Start()        ' Buffer for reading data
        Dim bytes(1024) As Byte
        Dim data As String = Nothing
        While True
            ' Enter the listening loop.
            MsgBox("Waiting for a connection...")
            ' Perform a blocking call to accept requests.
            ' You could also user server.AcceptSocket() here.
            Dim client As TcpClient = server.AcceptTcpClient()
            MsgBox("Connected!")
            data = Nothing            ' Get a stream object for reading and writing
            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)
                MsgBox("Received: " & data)
                ' Process the data sent by the client.
                data = data.ToUpper()
                Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)                ' Send back a response.
                stream.Write(msg, 0, msg.Length)
                MsgBox("Sent: " & data)                i = stream.Read(bytes, 0, bytes.Length)            End While            ' Shutdown and end connection
            client.Close()
        End While

解决方案 »

  1.   

    为什么不用WinScok控件呢?
      

  2.   

    vb.net么?
    用多线程吧.
    把监听while放sub里
      

  3.   

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim t1 As Threading.Thread
            Dim t2 As Threading.Thread
            t1 = New Threading.Thread(AddressOf 你的sub)
            t2 = New Threading.Thread(AddressOf 你的sub)
            t1.Start()
            t2.Start()
        End Sub