I need a UDP server that can communicate with many clients.
My current thinking is
- open a socket
- bind to a port
- recvfrom the client
- fork
- child: process the message, open a new socket and sendto the client
- parent: go to step 3
The server replies to the client on the same port from which the client connected, but from a random port.
I’ve implemented this, and with my test client, it works.
However, the real client is being written by someone else, somewhere else. (It’s an embedded system)
His client is expecting a reply from the same port to which he sent the message. The only way I can seem to do this is by using the same socket, which does work.
My worry though, is that will cause problems if more than one client tries to connect at once.
How should this be done?
UDP sockets are much simpler then TCP ones. Just reply on the same socket with
sendto(2)with client address you got fromrecvfrom(2). No need to mess this threads, just do it in a loop.Edit 0:
To elaborate a bit after your comment – when you get a datagram on a UDP socket you don’t get a new socket descriptor like with TCP, so your parent still handles all the input. Now, do you plan on
fork(2)-ing a new process and then creating a new socket for every packet? Or do you want to keep track of source addresses and map them to child processes and setup some sort of message passing from parent to child? I wouldn’t do either. The overhead is just too great. Just do it inline.Then if your message rates are really high and your processing is really heavy – increase server socket receive buffer (
SO_RCVBUF,setsockopt(2)), look into threading your server splitting it into I/O and processing parts, look into lock-free queuing, etc. But that last part is a whole different story. Start simple.