Reputation: 45
A TCP server (using the java.io package) should be multi-threaded so that it can support several clients concurrently. However, a UDP server need not be multi-threaded to serve several clients concurrently. Can anyone explain why it is so?
Upvotes: 0
Views: 2245
Reputation: 63955
A (java.io
) TCP server needs to be multithreaded because the communication with each client happens over io streams. Communication blocks per stream every time you read/write a message.
A UDP server does not communicate via io streams. It communicates directly via single datagrams from all clients on the same channel.
Assume your server has 10 clients and it waits for any one of them to send.
TCP needs 10 threads, each calling the InputStream#read()
method and all block. At one point 1 will be woken up. The "message" does not need to contain the senders address because that's implied by having a stream / connection.
UDP needs 1 thread that calls the DatagramSocket#receive()
method. The packet will contain the sender address so the 1 thread can decide what to do.
Upvotes: 1