Multithreaded server app blocking

sgt_pinky

Regular
Joined
Jan 5, 2005
Messages
80
Location
Melbourne, Australia
Hi,

I have a multithreaded server app (Winforms) that I have converted to a service.

It has a thread that simply creates a new TcpListener and waits for a connection:

Visual Basic:
    Public Sub StartListeningThread()
        Do
            Dim ip As IPAddress = IPAddress.Any
            Server = New TcpListener(ip, 4000)

            Server.Start()
            Dim tcpTmp As TcpClient = Server.AcceptTcpClient
            Dim tcpClient As New RUHTcpClient
            tcpClient.Client = tcpTmp.Client
            Server.Stop()

            Connections.Add(tcpClient)
        Loop
    End Sub

This thread runs for the life of the application. The problem is that without using the command 'End', the application is blocking on this thread on the line:

Visual Basic:
Dim tcpTmp As TcpClient = Server.AcceptTcpClient

Server.AcceptTcpClient holds up everything. I have tried to Abort() the thread, etc, but that doesn't help.

I can solve the problem using 'End' in the Winforms app, but in the service it causes all kinds of problems, and the program is left running in the taskmanager, even though it says 'Stopped' in the Services manager.

TIA,

Pinky
 
LOL. Just solved it. Always the way. I have had this prob for 2 days, and I solve it immediately when I have just asked for help :S

Initially my TcpListener was a Sub-level variable. Then I made it a Class-level variable and created a new Sub:

Visual Basic:
    Public Sub StopServer()
        thConnect.Abort()
        If Not Server Is Nothing Then Server.Stop()
    End Sub

Ah dear. Thanks anyway ;-)
 
The AcceptTcpClient method is behaving as designed. It is a blocking operation and will do so until a remote client connects.

How the TcpListener class works is that it listens on a port (in your case 4000) and uses that port to setup new TCP connections. Once a TCP connection is established a new local port is actually used for the data exchange so the original report can remain open. Think of a web server. It listens on port 80 but, when web page is actually sent, it is done so using a different local port. TCP is a bidirectional protocol that guarantees data delivery. The local port remains in use until the connection is closed.

Here's some simple pseudo-code for what you want to do:

Code:
While (SERVER IS RUNNING)

    'Waiting for remote client to connect on port 4000

     NewClient = AcceptTcpClient

     'Do whatever you want with NewClient 
     '(some port other than 4000 is being used locally)

     ' Loop back and wait for another client

End
If you only want to accept a single client, then your original code will work.
 
Back
Top