user1712917
user1712917

Reputation: 315

How to become aware when DatagramSocket is in a receive state

I am running a UDP Java implementation using DatagramSocket where the receive is running on one thread and the sending operations are run on a separate thread. When my program starts up, I need to make a call out to a server and receive information back. The problem is, due to the threading, even though I start my receiving thread first, sometimes the send will go out first and when the server replies, the socket has not called receive() yet in the other thread. Since this thread blocks on the receive() line, I can't use a flag to verify that receive() has been called. Is there any way to check if the socket is currently blocking on receive() so that I can wait to send until I verify that condition?

Upvotes: 2

Views: 378

Answers (2)

user207421
user207421

Reputation: 310915

You don't need two sockets.

  1. Create a single DatagramSocket. It is in a 'receive state' immediately.

  2. Start a receiving thread that receives over the DatagramSocket.

  3. Start a sending thread that sends over the DatagramSocket.

The order of (2) and (3) doesn't really matter any more.

Upvotes: 0

Martin James
Martin James

Reputation: 24857

Start the tx thread from the rx thread just before the recvfrom() loop and put a sleep(2000) at the start of the tx thread before it too starts loping around its input queue, or whatever it does normally to get stuff to send.

Upvotes: 1

Related Questions