简体   繁体   中英

How does DatagramSocket receive packet everytime and does not stuck

I create a DatagramSocket. When I am waiting for the packet, I cannot do anything until the packet is received. If I want to do something, such as print something when I am waiting for the packet. How do I do it?

This is my code.

private DatagramSocket socket = new DatagramSocket(8080);
private DatagramPacket packet = new DatagramPacket();
bool b = true;
int x = 0;

do {
  socket.receive(packet);
  //if I receive a packet, print the payload of the packet
  System.out.println(x);
  x++;
} while (b);

I want to keep print the "x". If I receive a packet, I will print the payload of the packet.

or

Can I put the receive function on the background? When I receive a packet, I print it immediately.

For this case, you can use threads. You are giving your main thread to infinite loop so that you can't do anything outside of the loop. If you create one more thread and use it for receiving packets, then your main thread can do other works.

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