开发者

Simple UDP reader

I'm trying to read all traffic from UDP port 6610, and I can see the packets in Wireshark. I made a simple reader for this:

public class ReceiveUDP extends Thread {

private int port = 6610;
private byte[] buffer = new byte[256];
private DatagramSocket socket;
private DatagramPacke开发者_如何学JAVAt packet;

public ReceiveUDP() throws SocketException {
    socket = new DatagramSocket(port);
    packet = new DatagramPacket(buffer, buffer.length);
    System.out.println("Succesfull socket / packet creation");
}

@Override
public void run() {
    try {
        socket.receive(packet);
        System.out.println("Succeded!");
    } catch (IOException e) {
        System.out.println("Failed to receive packet"+e.getCause().getMessage());
    }
}

public static void main(String[] args) throws SocketException {
    new ReceiveUDP().start();
}

The printout is:

Succesfull socket / packet creation

I.e. the script locks up at socket.receive(packet). Am I missing something?


It doesn't quite lock on receive(), it blocks on receive(). Specifically, it will wait on the receive line until something turns up. For the purpose of debugging and testing, you might use something like:

socket.setSoTimeout(5000); // Block for max 5 seconds

while (true) {
   try {
      s.receive(packet);
      System.out.println("Succeded!");
      break;
   } catch (SocketTimeoutException ste) {
      // Timeout reached, log this and try again.
      // Possibly keep track of the total number of tries and give up 
      // (break) if it exceeds a threshold.
      System.out.println("Timeout reached, will try again");
   } catch (IOException iox) {
      System.out.println("I/O Error: " + iox.getMessage());
      break;
   }
}

It's generally not a bad idea to use a timeout on your sockets, this prevents your app from waiting indefinitely. Whether this makes sense for your depends on your use case of course.


Like Joachim Sauer pointed out, the destination IP was not set to my IP. Changing this solved my problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜