Reputation: 665
I have a simple server that has a main thread and accepts the Clients, and starts a new thread per client. So in this thread I want to make a another connection( UDP) with the client, but I am confused. If there are 10 Threads(Clients) running and all ten try to open a DatagramSocket with the same port, that will throw SocketBindException right? So how can i do this?
Upvotes: 2
Views: 2517
Reputation: 3541
Upvotes: 3
Reputation: 1359
In UDP messaging to your client, your TCP server behaves as the UDP sender, via a UDP socket. There is no such thing as UDP connection.
Upvotes: 0
Reputation: 8756
Bind will fail if the local port is already opened but there's nothing to stop you from opening multiple local ports, one for each worker thread. The server just sends replies to the remote ip/port that sent the message and the reply will go to the original sending thread.
If the server may be the first to send UDP back to the client, then you have to go through the added trouble of retrieving the local port after the bind and sending it to the server over the TCP channel (or picking a port number in advance and binding to it explicitly).
If UDP communication is one-way, you can bind a UDP port in the main thread and re-use it in all the worker threads. UDP is connection-less so there's no state that needs to be maintained.
Upvotes: 0
Reputation: 1406
Just use a different port for each UDP connection. Each thread can be passed two values, the client connected over TCP and the UDP port that thread can use to connect with the client, and it will use only that port. That way you don't have a clash, and the method starting the threads knows which thread is using which port for UDP.
Upvotes: 1