我通过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@422dc860EDIT2:发送者代码
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);发布于 2015-04-28 21:56:56
以下是正确的方法:
InetAddress group = InetAddress.getByName(GlobalConfig.MULTICAST_IP);
SocketAddress sockaddr = new InetSocketAddress(group,GlobalConfig.LOCAL_PORT);
ds = new MulticastSocket(sockaddr);
ds.joinGroup(group);这一点很重要,但在因特网上很难找到这样的例子:
SocketAddress sockaddr = new InetSocketAddress(group,GlobalConfig.LOCAL_PORT);
ds = new MulticastSocket(sockaddr);发布于 2015-04-28 22:31:01
我试着通过DatagramSocket和MulticastSocket发送--没关系。我总是收到两次口信。我不明白为什么! 编辑:我的LogCat: I/GatewayController:发送的消息..。
D/UDP packet received﹕ java.net.DatagramPacket@422dc860 D/UDP packet received﹕ java.net.DatagramPacket@422dc860这不是你两次收到同一条消息的证据。这是您总是接收到同一个字节数组的证据。尝试记录消息内容。
但是,多播是UDP,UDP不能保证交付,也不能保证单次传递或顺序传递,所以仍然有可能得到重复的信息。如果这在语义上很重要,您需要通过序列号来检测它。
https://stackoverflow.com/questions/29930036
复制相似问题