title: Socket Programming in C# - The Client Never Connects to the Server
body: <p>I'm not looking for a complete written solution, I only want to know what is going wrong, as it's part of a school assignment. Both classes are written by the teacher, so I assume something is going wrong on my computer, but I have no idea where to look. I searched for some other solutions and can't find any which is different from this one, except low-level solutions but I also got a low-level solution from my teacher and that also doesn't work.</p>
  
  <p>The server:</p>
  
  <pre><code>var ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
  TcpListener server = new TcpListener(ipAddress, clientPort);
  server.Start();
  TcpClient client = server.AcceptTcpClient(); // The server gets here
  StreamReader clientIn = new StreamReader(client.GetStream());
  StreamWriter clientOut = new StreamWriter(client.GetStream());
  clientOut.AutoFlush = true;
  while (true)
  {
      string msg = clientIn.ReadLine();
      Console.WriteLine(msg);
      clientOut.WriteLine(msg);  
  }
  </code></pre>
  
  <p>The client:</p>
  
  <pre><code>TcpClient client = new TcpClient("localhost", serverPort); //The client gets here
  StreamReader clientIn = new StreamReader(client.GetStream());
  StreamWriter clientOut = new StreamWriter(client.GetStream());
  
  clientOut.AutoFlush = true;
  
  while (true)
  {
      clientOut.WriteLine(Console.ReadLine());
      Console.WriteLine(clientIn.ReadLine());
  }
  </code></pre>
  
  <p>As the client is in a try-catch block, which is in a loop until he has the connection, he tries to connect to the server many times. The server isn't catched, as AcceptTcpClient just waits for a connection, but while they are on the same ip and on the port of the other process, they never reach any connection.</p>
  
  <p>The connections are started in separate threads, but the main thread seems to wait until one is finished, which is not what I expected. I tried to let them both sleep on various methods (with <code>Thread.Sleep(1000)</code>, <code>Thread.Sleep(0)</code> (documentation said that another thread would be scheduled if you'd do that) and <code>while(stopwatch&lt;1000ms) {for(i&lt;100000)}</code>), none of them helped. The main thread only has some progress at the moment that the sleep of the connection-thread is gone and the connection-thread again creates the client.</p>
  
  <p>The problem also arises on another W7 64 bits computer.</p>
  
  <p>Does anybody know what the problem is?</p>