[英]MulticastSocket receives message twice
我通过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);
我试图通过DatagramSocket和MulticastSocket发送-没关系。 我总是收到两次消息。 我不明白为什么!
编辑:我的LogCat:
I/GatewayController﹕ Message Sent ...
D/UDP packet received﹕ java.net.DatagramPacket@422dc860 D/UDP packet received﹕ java.net.DatagramPacket@422dc860
这并不表示您两次收到相同的消息。 有证据表明您总是收到相同的字节数组。 尝试记录消息内容。
但是多播是UDP,并且UDP不保证传递,单传递或顺序传递,因此仍然有可能获得重复。 如果在语义上很重要,则需要通过序列号进行检测。
这是正确的方法:
InetAddress group = InetAddress.getByName(GlobalConfig.MULTICAST_IP);
SocketAddress sockaddr = new InetSocketAddress(group,GlobalConfig.LOCAL_PORT);
ds = new MulticastSocket(sockaddr);
ds.joinGroup(group);
这很重要,但很难在Internet的示例中找到:
SocketAddress sockaddr = new InetSocketAddress(group,GlobalConfig.LOCAL_PORT);
ds = new MulticastSocket(sockaddr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.