making a server listen continually

fguihen

Well-known member
Joined
Nov 10, 2003
Messages
248
Location
Eire
i have a client connecting to a server. they exchange mesages fine the first time, but i dont know how to keep the server listening for a client indefinately. anyone give any pointers on this?
 
The .AcceptSocket method blocks until a connection is created. The method returns a socket. You need to pass this socket off to a different process that fires on its own thread.
C#:
private void StartServer()
{
    TcpListener server = new TcpListener(IPAddress.Any, 1234);
    server.Start();

    Socket socket;

    ChatSession chatSession;
    
    while (true)
    {
        // blocks until a connection is established
        socket = server.AcceptSocket();

        // when this fires the socket will be connected and the connection 
        // will actually be setup on a port other than 1234.  this allows
        // us to keep servicing future requests on port 1234.
        
        // for long running processes, the key is to somehow pass the socket 
        // off to another thread.  if you dont do this the server will
        // not be able to establish new connections while the process is still
        // running.

        chatSession = new ChatSession(socket);
        chatSessions.Add(chatSession);
    }
}
The "ChatSession" class would spawn a new thread to handle the communication on the socket, which would allow the while loop to iterate again and wait for a new incoming connection request.
 
perfect !!! exactly what i was looking for. couldnt get my head around this bit. thanks ! :)
 
VB Compatable

Gill Bates,
I was looking for this same info but for VB. Can you show me how to do this in VB. I too want to serve multiple clients simultaniously. I used to accomplish this with multiple winsock controls in VB6. I havent done it in .net. Thanks in advance.
 
Back
Top