tags:

views:

68

answers:

1

What I'm wondering is, am I allowed to do this

client_db.clients[numberOfClients].sock = listener.Accept();

For my networking class I'm writing a chat client and a server that it connects to. I have an array of client objects that contains various info about each of the people connecting to the server. Before when dealing with one client, I would have a socket be equal to listener.Accept, and then I'd do all my stuff with that socket. I incorrectly assumed I could use an array of sockets to have multiple TCP connections with multiple clients.

Is there a way to do this? I realize there are probably more efficient ways to do this, but I'm still getting the hang of network programming, and more importantly, my server is currently based around the idea of me using a socket array. If there's no way to do it, this is certainly a lesson I'll remember.

EDIT: I was under the impression this didn't work because I got an exception saying something about "cannot have multiple connections," though I can't get that exception again. Now I am getting an object error. I'm confused, I need to look into this some more..

+1  A: 

With TCP, you can only have one process listening on a port but, when it accepts the connection (as yours does), you get a whole different socket descriptor to carry on the session, so you can go back and listen on the original socket descriptor for another connection.

The uniqueness in TCP is at the session level. In other words, the 5-tuple (source-ip, source-port, dest-ip, dest-port, protocol) must be unique in order for packets to not become confused about where they're going.

You can have thousands of clients talking to a given dest-ip/dest-port pair (like the large number of people hitting stackoverflow.com:80 right now).

So yes, you are allowed to do what you're doing.

What you may find is, if you try to bind to that port while there are still sessions in TIME_WAIT state, you won't be allowed to bind. This is to stop any live packets from a previous session on the network from coming in and spoiling your session.

More information on TIME_WAIT and why it's needed can be found in this excellent answer :-)

paxdiablo