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.
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.