TCP Over Internet with Port Forwarding C#

I am creating a TCP chat server/client.

The server/client work fine when connecting on a LAN network but I experience difficulties when connecting on different networks.

The strategy:

The client tries to reach the server's router who port forwards the data to the server.

So here is some code.

Server:

public static void Main (string[] args){ Console.WriteLine("Creating server: ."); StartTCPServer(null); } private static void StartTCPServer(object state) { TcpListener tcpServer = new TcpListener(IPAddress.Parse("10.0.1.164"), 5442); Console.WriteLine("I am listening for connections on " + IPAddress.Parse(((IPEndPoint)tcpServer.LocalEndpoint).Address.ToString()) + "on port number " + ((IPEndPoint)tcpServer.LocalEndpoint).Port.ToString()); tcpServer.Start(); Console.WriteLine("Server created. Awaiting client!\n"); TcpClient client = tcpServer.AcceptTcpClient(); Console.WriteLine("Client connection accepted from " + client.Client.RemoteEndPoint + "."); while(client.Connected){ byte[] buffer = new byte[1500]; int bytesRead = 1; while (bytesRead > 0) { bytesRead = client.GetStream().Read(buffer, 0, 1500); if (bytesRead == 0) { break; } Console.Write("\nMessage Recieved: " + System.Text.Encoding.UTF8.GetString(buffer)); buffer = new byte[1500]; bytesRead = 1; break; } } } 

And now the client:

public static void Main (string[] args){ TcpClient tcpClient = new TcpClient(); int attempts = 0; bool connected = false; bool showConnectionMessage = true; while(!tcpClient.Connected){ try{ attempts ++; tcpClient.Connect(new IPEndPoint(IPAddress.Parse(ROUTERS IP ADDRESS), 5442)); }catch{ tcpClient = new TcpClient(); Console.Clear(); if(connected){ Console.WriteLine("The server: , has lost connection!"); } Console.WriteLine("Connecting to server: Attempt: " + attempts); } Thread.Sleep(500); } if(tcpClient.Connected && showConnectionMessage){ showConnectionMessage = false; Console.WriteLine("Connected to server: \n"); attempts = 0; } while(tcpClient.Connected){ connected = true; Console.Write("Message: "); Byte[] sendBytes = Encoding.UTF8.GetBytes (Console.ReadLine()); tcpClient.GetStream().Write (sendBytes, 0, sendBytes.Length); Console.WriteLine("Message sent\n"); } if(!tcpClient.Connected && connected){ Console.WriteLine("The server: , has lost connection!"); tcpClient.Close(); } } 

I use an apple airport as my router so here is a screenshot of the port forwarding. The IP address the router forwards to is the one the server connects to. http://ift.tt/1QQ9Dc3

Any help is appreciated!

Thanks in advanced.

by Senior-Jesticle via /r/csharp

Leave a Reply