问题
I am trying to test UDP communications on a LAN. I have a small piece of code to and I have tried to run it in 2 computers (one should wait to receive and the other one should send). The strange thing is that computer A sends and B receives properly but if I try A to receive and B to send it does not work. Do you know why could it be?
public void SendBroadcast(int port, string message)
{
UdpClient client = new UdpClient();
byte[] packet = Encoding.ASCII.GetBytes(message);
try
{
client.Send(packet, packet.Length, IPAddress.Broadcast.ToString(), port);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void Receive(int port)
{
UdpClient client = null;
try
{
client = new UdpClient(port);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
IPEndPoint server = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
byte[] packet = client.Receive(ref server);
Console.WriteLine("{0}, {1}", server, Encoding.ASCII.GetString(packet));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
And the calls:
SendBroadcast(444, "hello"); Receive(444);
If I run 2 instances of the program on the same computer it works properly but creates 3 packages per call.
Thanks in advance.
回答1:
Well, if the same code works on one and not the other, it's your environment. Check your firewall settings, make sure it's not preventing the broadcast on the sender or preventing receipt on the receiver. Wireshark (or even Windows' netmon) should be helpful here.
回答2:
Try using the async methods so that you can keep listening for messages without blocking to send messages.
回答3:
What networking gear is inbetween these two systems?
Are the two systems on the same subnet with the same subnetmask?
There's a funny thing with IPV4 networks; you can have multiple broadcast addresses. You can broadcast to the local network or to the local subnet. These are distinctly different addresses, and if one system's IP setup is different it may not realize that it should listen for this local subnet broadcast.
Things to try:
- Ensure IPV6 is disabled on both ends (IPV6 doesn't support broadcast address, but lets just establish a baseline).
- Explictly set the IP address in the program, does it work? My guess will be yes, so we have to determine why.
- Load up wireshark and sniff the packets. See if they are making it all the way to the remote host, and he is just ignoring them.
回答4:
When trying to do this asynchronously, Microsoft neglects to tell users to create their own partial class like this (see below). Very simple, but without this, it can be difficult to read through their examples.
private partial class UdpState
{
public UdpClient u;
public IPEndPoint e;
}
来源:https://stackoverflow.com/questions/6695669/sending-and-receiving-udp-packets-in-net