Design – Non Blocking Sockets vs Blocking sockets – UDP – C&linux

cdesignnetworkingprotocolsockets

When to use blocking sockets over non blocking sockets on UDP?

Question 1:What's is recommended for the following scenario ?

Multiple clients send data over multiple UDP sockets, i.e. say client1 sends data over sockets 100, 101, 102,..,105 . client2 on sockets 110,111,112…115 etc. Port numbers are fixed for clients. Number of clients are fixed(10).
So totally 10 * 5 sockets.

Data on each sockets(atleast 3 sockets) is sent every few milliseconds.
The other 2 sockets are for sending commands and getting data.

After receiving the data there is some IO involved where i write to disks.
(I cant change any of the above. i.e. number of sockets ,etc )

Question 2:Is it best to use Threads for this scenario (or) Asynchronous IO multiplexing with nonblocking sockets?

Best Answer

The usual way is to use poll() or select(), which ever you find more to your liking, with blocking sockets. Since they accept any file descriptors, same loop can be used for inter-thread or inter-process communication with a socket pair, or reading input from stdin.

A good, quite short and to the point, reading is Beej's Guide to Network Programming Using Internet Sockets. Check out section about select() for a small example program source. That uses TCP and not UDP, so you'll need to do some adapting, but UDP will probably just make things simpler (unless your use case is re-implementing TCP functionality on top of UDP, which almost never is a good idea).

You may want to do processing in separate threads (or even processes, depending on requirements), or just inside that same loop, depending on how heavy this is: "After receiving the data there is some IO involved where i write to disks." I'd start with a single-threaded implementation and see how it goes, before making it more complex.

Related Topic