VB,.Net非阻塞TcpClient

时间:2019-05-13 17:04:08

标签: .net vb.net

我有一个TCP侦听器的工作示例,该侦听器在特定的PORT上接收数据,并在需要时发送响应。问题在于,当脚本发送响应时,整个过程正在等待,并且不接受新连接。也许有人可以帮助改善代码,使其开始接受新的连接而不会阻塞?

Public Shared Sub test()
        Dim listener As TcpListener = Nothing
        Dim port As Integer = 555

        Try
            listener = New TcpListener(IPAddress.Any, port)
            listener.Start()

            'Buffer for reading data
            Dim bytes(1024) As Byte
            Dim data As String = Nothing

            ' Enter the listening loop.
            While True
                Console.Write("Waiting for a connection... ")
                ' Perform a blocking call to accept requests.
                ' You could also use server.AcceptSocket() here.
                Dim client As TcpClient = listener.AcceptTcpClient()
                Console.WriteLine("Connected!")

                data = Nothing

                ' Get a stream object for reading and writing
                Dim stream As NetworkStream = client.GetStream()

                ' Loop to receive all the data sent by the client.
                Dim i As Integer = stream.Read(bytes, 0, bytes.Length)

                While (i <> 0)

                    ' Translate data bytes to a ASCII string.
                    data = Encoding.ASCII.GetString(bytes, 0, i)
                    Console.WriteLine("Received: {0}", data)

                    If data.Contains("ppp") Then
                        Console.WriteLine("Contains ppp")
                        ' Send back a response.
                        Response(stream, "my_response")
                    End If

                    i = stream.Read(bytes, 0, bytes.Length)
                End While
                ' Shutdown and end connection
                Console.WriteLine("connection closed")
            End While
        Catch e As Exception
            Console.WriteLine(e)
        Finally

            If listener IsNot Nothing Then
                listener.Stop()
            End If
        End Try

    End Sub

    Public Shared Sub Response(stream As Object, message As String)
        Dim response As Byte() = Encoding.ASCII.GetBytes(message)
        stream.Write(response, 0, response.Length)
        Console.WriteLine("response {0} sent", message)
    End Sub

0 个答案:

没有答案