问题描述
我有2个节目,1用于发送UDP广播消息,1被监听这个广播。我的问题是,有时当我发送一个广播,接收器接收2个消息。为什么呢?
接收器code:
公共类接收器{
私人只读UdpClient UDP =新的UdpClient(15000);
私人无效StartListening()
{
this.udp.BeginReceive(接收,新的对象());
}
私人无效接收(IAsyncResult的AR)
{
IPEndPoint IP =新IPEndPoint(IPAddress.Any,15000);
字节[]字节= udp.EndReceive(AR,楼盘IP);
字符串消息= Encoding.ASCII.GetString(字节);
StartListening();
}
}
发件人code:
公共类发件人{
公共无效的send(){
UdpClient客户端=新UdpClient();
IPEndPoint IP =新IPEndPoint(IPAddress.Broadcast,15000);
字节[]字节= Encoding.ASCII.GetBytes(富);
client.Send(字节,bytes.Length,IP);
client.Close();
}
}
严格地说,在IP网络数据包复制允许网络的行为,你必须要能够处理它在你的软件,即使你会以某种方式得到摆脱它这个时候。如果你只是想知道为什么会这样你的具体情况......在第一眼看到我没有错你的code。你有你的电脑的以太网端口或一些这样的几个IP地址?我觉得可能有助于获得有关发生了什么事情的更多细节。
I've got 2 programs, 1 for sending an UDP broadcast message and 1 that is listening for this broadcast. My problem is that sometimes when I send a broadcast, the receiver receives 2 messages. Why?
Receiver code:
public class Receiver {
private readonly UdpClient udp = new UdpClient(15000);
private void StartListening()
{
this.udp.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 15000);
byte[] bytes = udp.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
StartListening();
}
}
Sender code:
public class Sender {
public void Send() {
UdpClient client = new UdpClient();
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 15000);
byte[] bytes = Encoding.ASCII.GetBytes("Foo");
client.Send(bytes, bytes.Length, ip);
client.Close();
}
}
Strictly speaking, packet duplication in IP network is allowed behavior of the network and you have to be able to deal with it in your software even if you will somehow get rid of it this time. If you are just wondering about why this happens in your particular case... at a first glance I see nothing wrong with your code. Do you have several IP addresses on Ethernet port of your computer or some such? I think wireshark might help get more details about what's going on.
这篇关于发送UDP广播,接收多条消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!