Search code examples
c#udpserverclient

C# UdpCLient.Receive doesn't receive any data on different machine


Hi guys i'm developing an application in c# with a server and lots of clients, i need them to comunicate in particular the server must sends one packets to all the client, this hapens at random time ( it sends the packet only when another program send a signal that i capture). I didn't want to use TCP because this must be as fast as possible and because i have lots of client ( they can be more than a thousand).

I tried some solution with UDP, with broadcast and multicast and also with a loop sending the packets to all of them singularly. I tested it with 1 server and 2 clients, both of these solution works fine when they are on the same machine but when i put it on the internet (server on a machine and the client on another machine in different network) the program doesn't work anymore, the clients don't receive anything.

Sender:

private void send(string packet){

        /* code to get the key to encript the data */

        byte[] bytes = Encryptor.EncryptString(packet, key); 

        query = "SELECT ip FROM utenti WHERE ID <> 2";
        List<string> ips = SelectIPs(query);

        foreach (string ip in ips){
            if (ip == "")
                continue;
            UdpClient client = new UdpClient();
            IPAddress address = IPAddress.Parse(ip);
            IPEndPoint ipEndPoint = new IPEndPoint(address, 16759);
            client.Send(bytes, bytes.Length, ipEndPoint);
            client.Close();
        }    
    }

Receiver:

private void receive(string packet){

      receivingUdpClient = new UdpClient(16759);
       RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse("185.43.209.118"), 0);
       byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

       /* code to get the key to decrypt */ 
       string returnData = Encryptor.DecryptString(receiveBytes, key);

       Console.WriteLine(returnData);
       return;
}

I posted the solution with the loop in the send but i also tried with broadcast and multicast.

Any suggestion on what to do and why i don't receive anything if they are on different machine?


Solution

  • Acorrding to your explanation(that it doesn't work only on another machine) and to your code, it seems like to be a port forwarding problem. You can read more about it here: https://en.wikipedia.org/wiki/Port_forwarding

    Port forwarding basically is mapping your external port to an internal adress, so your computer can communicate with computers in others networks.

    You can use UPnP libraries in c#, such as Open.Nat , which supports the port forwarding in c#. (Your router should enable port-forwarding to allow Open.nat to work).

    Goodluck.