2011-08-25 95 views
3

我試圖從UDP端口6610讀取所有流量,並且我可以在Wireshark中看到數據包。我給這個簡單的讀者:簡單的UDP閱讀器

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

你如何發送數據包?換句話說:*你期望它得到什麼*? –

+0

您是否期望接收單播或廣播UDP數據包? –

+0

@Joachim - 我是UDP的新手 - 我必須*發送*什麼東西才能接收內容?我希望收到在這個端口發送的一切...... – Theodor

回答

1

它並不完全鎖定在,它在。具體來說,它會在接收線上等待,直到出現問題。對於調試和測試的目的,你可以使用這樣的:

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; 
    } 
} 

這通常不是一個壞主意,使用超時你的插座,這樣可以防止您的應用程序無限期地等待。這對你來說是否合理取決於你的使用案例。

0

就像Joachim Sauer指出的那樣,目標IP沒有設置爲我的IP。改變這個解決了我的問題。