Socket per user?

Started by
1 comment, last by ChristianPena 18 years, 3 months ago
Hi, This is possibly a C# specific question, but I do not think it is. I am wondering if I should store a new Socket for each client or just an EndPoint for them and have one Socket which sends to all clients. My second question is: Should I have all clients communication on one port or should I assign clients to different ports at runtime, possibly as part of the handshaking procedure, and then have the main port just accepting connection requests. Thanks!
Advertisement
The answers to this question are going to be different depending on whether or not you are using TCP or UDP.

With TCP you have to have a seperate socket for each client, with UDP you don't.

TCP you create a listen socket, that only listens for connections. When a connection occurs, you call Accept(), which creates a new socket for the connection. All communication to and from that client will then occur on the new socket. (This socket will have a different port from your listen socket.. but TCP deals with the allocation and handshake by itself).

UDP you can use a single socket/port, but there is more programmer management involved.


I prefer to use a single UDP socket, and then in my code, I create custom "virtual" sockets (A higher level data structure that my games use. The UDP socket recieves data, parses the application specific header, and dispatches it to the "virtual" socket.. The opposite happens on a send).

This reduces the amount of memory needed per connection, and also makes it easier for the end user to open up ports on his firewall or NAT. (he only needs to upen up a single port, instead of a range of ports).

Most of this functionality is probably already abstracted in other network libraries (Read the FAQ for a list of them).

I personally prefer to write my own winsock abstraction layer, but I've been doing this for a looong time, and am a control freak :) If you are less experienced with winsock, I would reccomend looking into one of the other freely available libraries. Otherwise you will end up writing your own reliable transport code, which can be a real bear to get right.



I am using UDP in C#. I will go with one socket and one port. This is a small game, perhaps 16 players at most.

I am also a control freak. I will likely end up writing a transport layer, but since there is so much knowledge and experience that the members on this board possess, I figure I can learn some best practices here instead of learning every small lesson.

Thanks for the input. I will try it out and will probably write an article about it for GameDev when done.

This topic is closed to new replies.

Advertisement