.Net non-blocking TcpClient

  • Thread starter Thread starter lifeisshort
  • Start date Start date
L

lifeisshort

Guest
I have working example of TCP listener which receives data on particular PORT and if needed sends response. The problem is that when script sends response whole process is waiting and doesn't accept new connections. Maybe someone can help to improve code so it start accepting new connections without blocking?

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

Continue reading...
 
Back
Top