Multiuser Help!

kleptos

Well-known member
Joined
Jul 16, 2003
Messages
47
Location
Boca Raton, FL
I am trying to build a small chat server that will allow multiple users to connecto to it, accept incoming messages and echo back to all connected clients. I am sorta new to sockets and not sure how to implement multiple users connecting to my TcpListener. Any help or pointers in the right direction would be most helpful. I have yet to find an example of this through out the quick starts and the msdn library. Thanks!
 
Here is how I would do it, I am assuming you are using C# but regardless the same theories apply to any language. I adapted this from what I had been doing in C++ previously.

You will need two ArrayLists, one for the master list of all connected sockets and another as a copy of the master for iterating through etc.

First you will need to setup a socket to represent the server (create it, bind it, listen). Add it to the master socket ArrayList.

Now, within the mainloop of your application you will need to do some looping. First, set the socket copy list equal to the master. Now, we will need a foreach() loop to iterate through every socket in the copy list.

We need to check if there is data waiting on the socket, so we have a few options for this. We can use System.Net.Sockets.Socket.Select() or we can use System.Net.Sockets.Socket.Poll(). I am partial to Polling sockets so thats what I will use.

At the begining of the loop, we have an if statement to see if poll() returns true or false. If it is true, then we can proceed with this socket. Otherwise, we ignore this socket and move on.

The first thing we need to do, is see if the current socket is the server socket. If it is, then that means that we have a new connection attempt. Accept() the connection and add it to the master list.

If it isnt the server socket, then it is another client that is already connected and we should recieve the data.

If the recieve method returns a value less than or equal to 0, that means that the socket is disconnecting or the connection was interupted etc.

I think that pretty much sums it up. Im hoping I didnt leave anything out.

Ah yes, if you need an example program let me know and I will put one together for you.
 
Back
Top