我通过 MulticastSocket 向 WIFI 接入点发送消息,并且总是得到两次回复。如果我尝试向自己发送消息,我会再次收到两次消息。这是我的接收器代码:
protected Void doInBackground(Void... params) {
String lText;
byte[] lMsg = new byte[GlobalConfig.MAX_UDP_DATAGRAM_LEN];
DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
MulticastSocket ds = null;
try {
ds = new MulticastSocket (32001);
InetAddress serverAddr = InetAddress.getByName("224.237.124.120");
ds.joinGroup(serverAddr);
while (serverActive) {
ds.receive(dp);
Log.d("UDP packet received", dp.toString());
lText = new String(lMsg, 0, dp.getLength());
receivedMessage = lText;
doSomething();
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
return null;
}
我尝试通过 DatagramSocket 和 MulticastSocket 发送 - 无论如何。我总是收到两次消息。我不明白为什么!
编辑:我的 LogCat:
I/GatewayController﹕ Message Sent
...
D/UDP packet received﹕ java.net.DatagramPacket@422dc860
D/UDP packet received﹕ java.net.DatagramPacket@422dc860
EDIT2:发件人代码
protected Void doInBackground(Void... params) {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName("224.237.124.120");
DatagramPacket dp;
dp = new DatagramPacket(byteMsg, byteMsg.length,
serverAddr, 32000);
ds.send(dp);