2014-03-31 30 views
2

在我的Android應用程序中,我發送一個UDP廣播到地址255.255.255.255,端口6400.我使用PC程序Packet Sender作爲UDP服務器,自動發送回覆。沒有回覆UDP廣播,只有單播

當我在Android應用程序中收聽此回覆時,它從未收到回覆。如果我不將數據包發送到255.255.255.255,而是發送到PC的特定IP地址,我只能收到答覆。

private String udpDestinationAddress = "255.255.255.255"; 
private int udpDestinationPort = 6400; 
private int udpTimeoutMs = 5000; 
private String udpData = "test"; 

DatagramSocket socket; 
socket = new DatagramSocket(12345); 
socket.setBroadcast(true); 
socket.setSoTimeout(udpTimeoutMs); 
socket.connect(InetAddress.getByName(udpDestinationAddress), udpDestinationPort); 

// send part 
byte[] data = udpData.getBytes(); 
int length = data.length; 
DatagramPacket packet = new DatagramPacket(data, length);    
socket.send(packet); 

// receive part 
byte[] buffer = new byte[1000]; 

// Initialize the packet 
DatagramPacket packet = new DatagramPacket(buffer, buffer.length); 

// Receive the packet 
socket.receive(packet); // it timeouts here (if timeout=0, then it hangs here forever) 

// Get the host IP 
String hostIP = packet.getAddress().toString().replace("/", ""); 

在PC程序,我已經將它設置爲自動(另一個隨機字符串)與我測試過的其他應用程序(不同的UDP測試Android應用程序)回覆包在端口6400。這工作得很好。但是,我的應用似乎無法獲得答覆。

當我將udpDestinationAddress設置爲PC的特定IP時,我只能在我的應用程序中獲得回覆。我也試過「192.168.5.255」(在本地子網上廣播)而不是「255.255.255.255」 - 仍然不起作用。

+0

我有這種事發生在我偶爾。有時網絡會丟棄數據包或不會轉發數據包。根據不同的網絡我運行它有時它有效它不會 –

+0

您的網絡路由器必須允許多播/廣播這個工作... –

+0

@GermannArlington - 路由器已經允許。 – eightx2

回答

1

我發現了這個問題。

取而代之的是將目標IP和端口綁定到socket,我需要將它綁定到packet

代替,:

socket.connect(InetAddress.getByName(udpDestinationAddress), udpDestinationPort); 
... 
DatagramPacket packet = new DatagramPacket(data, length); 

...用這個來代替:

InetAddress addr = InetAddress.getByName("255.255.255.255"); 
DatagramPacket packet = new DatagramPacket(udpData.getBytes(), udpData.length(), addr, udpDestinationPort);