continue accepting tcp-connections in thread

pettab

Newcomer
Joined
Feb 15, 2006
Messages
1
I have this code running in a thread, I want it to continue listen on that port for more incoming connections but can't get it to work, how to do this?

Code:
' Must listen on correct port- must be same as port client wants to connect on.
        Const portNumber As Integer = 8000
        Dim tcpListener As New TcpListener(portNumber)
        tcpListener.Start()

        Try
            'Accept the pending client connection and return 
            'a TcpClient initialized for communication. 
            Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
            Console.WriteLine("Connection accepted.")
            ' Get the stream
            Dim networkStream As NetworkStream = tcpClient.GetStream()
            ' Read the stream into a byte array
            Dim bytes(tcpClient.ReceiveBufferSize) As Byte
            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
            ' Return the data received from the client to the console.
            Dim clientdata As String = Encoding.ASCII.GetString(bytes)
            'Console.WriteLine(("Client sent: " + clientdata))
            ToDoFlash.Enqueue(clientdata)
            Dim responseString As String = "Tog emot: " & clientdata
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            Console.WriteLine(("Message Sent /> : " + responseString))
            'Any communication with the remote client using the TcpClient can go here.
            'Close TcpListener and TcpClient.
            'tcpClient.Close()
            'tcpListener.Stop()

        Catch e As Exception
            'Console.WriteLine(e.ToString())
        End Try
 
Your problem is that you need to place your code in a loop. The "AcceptTcpClient" function of the "TcpListener" class returns a socket for the newly established connection (when a remote client connects). This function waits in blocking mode until a client connects. When somebody connects, you need to pass the underlying socket off to some other process (asynchronously). This will allow the loop to continue to its next iteration and start waiting for a new connection.

The original port that you designate for the TcpListener is simply the port that the server listens on to establish connections on other ports.
 
Also note that if you have a socet listening and accepting sockets, NEVER reuse an old socket without both .Shutdown() and .Close and then socket = Nothing before stuffing another socket into your var that holds the socket, otherwise, you could LOST CONTROL of an open socket, and it would time out and consume memory and processor time maintaining it until you reboot the computer!
 
Back
Top