title: C# Sockets over the internet
body: <p>I successfully made a client server program in C# working perfectly under a LAN, we used the TcpListener and TcpSocket class.</p>
  <p>We could not get it to work over the internet though, I understand that it has to do with firewalls, router port blocking etc.</p>
  <p>We forwarded the port we used and turned off our firewalls and still no luck.</p>
  <p>What do I have to do differently in order to make this work? Like a certain port to use that will work without issues? How does say &quot;Msn Messenger&quot; do it?</p>
  <p>Server Code:</p>
  <pre><code>  private static TcpListener serverTcpListener;
  
     public static bool Run()
      {
          // Initialize new thread for client communications
          Thread listenThread = new Thread(new ThreadStart(ListenForClients));
          
          // Initialize TCP listener and attempt to start
          ServerTcpListener = new TcpListener(IPAddress.Any, 3000);
  
          try
          {
              ServerTcpListener.Start();
          }
          catch (SocketException)
          {
              return false;
          }
  
  
          // Start client communications thread
          listenThread.Start();
  
          return true;
      }
  
  
  
  
  
      
      public static void ListenForClients()
      {
          while (true)
          {
              TcpClient client = ServerTcpListener.AcceptTcpClient();
              Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
              clientThread.Start(client);
          }
      }
  </code></pre>
  <p>Client Code:</p>
  <pre><code>    private TcpClient myClient;
      private NetworkStream clientStream;
  
     public InitializeResult Initialize()
      {
          IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(&quot;127.0.0.1&quot;), 3000);
  
          try
          {
              MyClient.Connect(serverEndPoint);
          }
          catch (SocketException)
          {
              return InitializeResult.AccessError;
          }
          catch (ArgumentNullException)
          {
              return InitializeResult.NullRemote;
          }
  
          try
          {
              ClientStream = MyClient.GetStream();
          }
          catch (Exception)
          {
              return InitializeResult.StreamFail;
          }
  
          if (!Authenticate())
          {
              return InitializeResult.AuthenticateFail;
          }
  
  
          return InitializeResult.Success;
          
      }
  </code></pre>