我正在尝试从UDP端口6610读取所有流量,我可以在Wireshark中看到这些数据包。我为此做了一个简单的读者:
public class ReceiveUDP extends Thread {
private int port = 6610;
private byte[] buffer = new byte[256];
private DatagramSocket socket;
private DatagramPacket 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();
}
打印输出为:
Succesfull socket / packet creation
即。脚本锁定在socket.receive(packet)
。
我错过了什么吗?
答案 0 :(得分:1)
它并没有完全锁定receive()
,而{em>阻止 receive()
。具体来说,它将在接收线上等待,直到出现问题为止。出于调试和测试的目的,您可以使用以下内容:
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;
}
}
在套接字上使用超时通常不是一个坏主意,这可以防止您的应用无限期地等待。这对您来说是否合理取决于您的用例。
答案 1 :(得分:0)
就像Joachim Sauer所指出的那样,目的地IP没有设置为我的IP。改变这个解决了我的问题。