zedrummer
Member
- Joined
- Oct 9, 2023
- Messages
- 5
- Programming Experience
- 10+
Hello
To detect the server for a connection, the server broadcasts its address through this UDP code sent each second:
Then the clients check the messages broadcast with this code called over and over:
I have a desktop connected to the router (local network) via Ethernet and a laptop connected via Wifi. If I start the server on the laptop, the message is received by the desktop, but if I start the server on the desktop, I always get a time out message. I've checked the firewall and for both computers, the app is unblocked. Any idea, please?
Thanks
David
To detect the server for a connection, the server broadcasts its address through this UDP code sent each second:
C#:
private static void BroadcastDiscovery()
{
while (isBroadcasting)
{
byte[] discoveryData = Encoding.UTF8.GetBytes("Server_IP: " + localIpAddress);
udpClient.Send(discoveryData, discoveryData.Length, new IPEndPoint(IPAddress.Broadcast, DISCOVERY_PORT));
Thread.Sleep(1000); // Wait for 1000 milliseconds before sending the next broadcast
}
} // Function to get the local IP address
Then the clients check the messages broadcast with this code called over and over:
C#:
public static string ListenForDiscoveryMessages()
{
udpClient = new UdpClient(DISCOVERY_PORT);
udpClient.EnableBroadcast = true;
try
{
udpClient.Client.ReceiveTimeout = 2000;
while (true)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, DISCOVERY_PORT);
byte[] receivedData = udpClient.Receive(ref remoteEndPoint);
string message = Encoding.UTF8.GetString(receivedData);
Debug.WriteLine($"Received discovery message: {message}");
if (message.Substring(0, DISCOVERY_MESSAGE.Length) == DISCOVERY_MESSAGE)
{
Server_IP = message.Substring(DISCOVERY_MESSAGE.Length);
udpClient.Close();
return Server_IP;
}
}
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.TimedOut)
{
Debug.WriteLine("Discovery message reception timed out.");
}
else
{
Debug.WriteLine($"SocketException: {ex.Message}");
}
}
udpClient.Close();
return "";
}
I have a desktop connected to the router (local network) via Ethernet and a laptop connected via Wifi. If I start the server on the laptop, the message is received by the desktop, but if I start the server on the desktop, I always get a time out message. I've checked the firewall and for both computers, the app is unblocked. Any idea, please?
Thanks
David