简体   繁体   中英

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?

在recvfrom()循环之前从rx线程启动tx线程,并在tx线程开始绕入其输入队列或执行通常的操作以获取发送内容之前,在tx线程的开始处放置sleep(2000)。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM