Jules Testard
Jules Testard

Reputation: 73

UDP Socket.receive() method used in multithreaded environments

I was looking for this information and could not find it elsewhere: I am building a multiplayer game with a server and a fixed number of clients. Our clients are multithreaded (one thread for the game logic and visualization, one thread for receiving messages) and may receive messages from the server asynchronously. Communication is acheived using UDP.

What happens if the former thread makes a call to the socket.receive() method while the latter thread goes through a loop that uses socket.receive() as well?

More specifically, if a message arrives from the server and two threads are waiting for reception at the same time, is the message received for both threads? If not, is it defined which thread will receive the packet?

Note that both threads are using the same socket.

Upvotes: 0

Views: 502

Answers (2)

user207421
user207421

Reputation: 310903

The message is received once, by the first thread to enter the receive() method.

Under the hood this is achieved by the fact that PlainSocketImpl.receive() is synchronized.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500515

I don't know, offhand - but I'd simply avoid that situation coming up in the first place.

You say that the first thread is for game logic and visualization, and the second is for receiving messages - so why on earth would the first thread be calling socket.receive()? That's not its job, and it certainly should be blocking if it's meant to be displaying things.

Having a dedicated thread for receiving messages sounds like a perfectly reasonable idea to me - so stick to that plan instead of mixing up responsibilities between the two threads.

Upvotes: 1

Related Questions