Problem sending a message

0

I've made a snippet of code that sends a message via TCP / IP with sockets from one computer to another. It works well (sends the message) if the two computers are connected to the same network, however, if I connect one of the two computers to a different wifi does not work.

I do not know if the problem is that I must open ports or if I have to put an IP different from the local one of the computer.

The code snippet is as follows:

private void Envio()
{
   //Ejemplo de IP
   IPAddress IP = IPAddress.Parse("192.168.1.40");

   TcpClient TCP = new TcpClient();
   await TCP.ConnectAsync(IP, 443);

   Stream Str = TCP.GetStream();

   if (Str.CanWrite == true)
   {
      var Mensaje = Encoding.ASCII.GetBytes("Hola");

      if (Str != null)
      {
         Str.Write(Mensaje, 0, Mensaje.Length);
      }
   }

   TCP.Dispose();
}

private void Recepcion()
{
   IPAddress IP = IPAddress.Parse("192.168.1.40");

   TcpListener TCP = new TcpListener(IP, 443);
   TCP.Start();

   MensajeB[] buffer = new byte[256];
   string Mensaje = null;

   bool Seguimiento = true;
   while (Seguimiento == true)
   {
      TcpClient TCPCl = await TCP.AcceptTcpClientAsync();
      ResultPrueba.Text = "Conectado";

      datos = null;

      NetworkStream NetStr = TCPCl.GetStream();

      int i;
      while ((i = NetStr.Read(MensajeB, 0, MensajeB.Length)) != 0)
      {
         datos = Encoding.ASCII.GetString(MensajeB, 0, i);
         ResultPrueba.Text = datos;
      }

      TCPCl.Dispose();
      if (datos.Length > 0)
      {
         Seguimiento = false;
      }
   }
}
    
asked by MTKt 05.08.2017 в 13:58
source

1 answer

1

If you connect 2 computers to different networks the following happens:

-The network A receives the public IP, xxx.xxx.xxx.xxx . And pc 1 is assigned a local IP: 192.168.1.40 .

-The network B receives the public IP, yyy.yyy.yyy.yyy . And pc 2 is assigned a local IP: 192.168.1.41 .

If they are in the same network you can connect one PC to another using local IP's, but being in different networks you can not communicate with the local IP without going through the public IP. For that you have to connect to the public IP, that is to say the router, for example of A . And for that to work, you have to open the port you want to use, and redirect traffic from that port to the corresponding local IP, in this case 1 .

You can probably get a guide on how to do this from your ISP, or simply search for it.

    
answered by 06.08.2017 / 13:25
source