title: TCP both Client and Server on the same PC
body: <p>I'm trying to implement a small tcp based application in C#. I'm new to TCP programming. </p>
  
  <p>The app is really simple. It's a client/server scenario, which support max 2 clients. One client will be an "external" IP, the other will be the host itself. </p>
  
  <p>Everytime a client connect to the server, it begins to receive and send packets from/to the server. </p>
  
  <p>I have set up a small console app which implements both TCP server side code and TCP client code. </p>
  
  <p>The server use a listener binded to a specific port and wait for client connections. Once a client is connected, it spawn a new thread to handle communication with the client.</p>
  
  <p>The client simply connect to the server and once the connection is estabilished it starts to receive and send pakcets.</p>
  
  <p>As I said before "the host is also client of itself", but this leads to an issue. If the client send a packet to the server, both server and client claims to have received a packet. It is normal? Am I missing something?</p>
  
  <p>UPDATE 2 (fixing issue)</p>
  
  <p>I think I've found the issue. I need to "reset" the buffer once the send operation is done by the client</p>
  
  <pre><code>          case SocketAsyncOperation.Send:                        
  
                // Put in listen mode
  
                // Buffer reset AFTER send and BEFORE receive
                _receiver.SetBuffer(new byte[4096], 0, 4096);
  
                _client.ReceiveAsync(_receiver);                        
  
                break;
  </code></pre>
  
  <p>UPDATE 1 (adding code)</p>
  
  <p><strong>Server</strong></p>
  
  <pre><code>    public void Host()
      {                        
          _listener = new TcpListener(new IPEndPoint(IPAddress.Any, this.ConnectionPort));
          _listener.Start();
  
          this.IsListening = true;            
  
          ThreadPool.QueueUserWorkItem((state) =&gt;
          {
              while (true)
              {
                  // Blocks until a client connections occours
                  // If continue with no client then stop listening                    
                  try
                  {
                      TcpClient client = _listener.AcceptTcpClient();
  
                      // Add client to peer list
                      long assignedID = DateTime.UtcNow.Ticks;
                      _clients.Add(assignedID, client);
  
                      HandleClient(assignedID);
  
                      if (this.ConnectedClients == this.MaxClients)
                      {
                          _listener.Stop();
  
                          this.IsListening = false;
  
                          break;
                      }
                  }
                  catch
                  {
                      // Server has stop listening
                      _stopListen.Set();
  
                      break;
                  }
              }
          });
      }
  
      private void HandleClient(long assignedID)
      {
          ThreadPool.QueueUserWorkItem((state) =&gt;
          {
              long clientID = (long)state;
              TcpClient client = _clients[clientID];        
  
              try
              {
                  byte[] message = new byte[4096];
                  byte[] buffer = new byte[4096];
  
                  int readed = 0;
                  int index = 0;
  
                  NetworkStream clientStream = client.GetStream();
  
                  while (true)
                  {                        
                      readed = clientStream.Read(message, 0, message.Length);
                      if (readed == 0)
                      {
                          // Client disconnected, thorw exception
                          throw new SocketException();
                      }
  
                      Array.Copy(message, 0, buffer, index, readed);
                      index += readed;
  
                      if (readed == 4096
                          &amp;&amp; !_packetHub.IsValidBufferData(buffer))
                      {
                          Array.Clear(buffer, 0, buffer.Length);
                          readed = 0;
                          index = 0;
  
                          continue;
                      }
  
                      if (_packetHub.IsValidBufferData(buffer))
                      {
                          NetPacket receivedPacket = _packetHub.DeserializePacket(buffer);
                          NetPacket answerPacket = null;
  
                          // Assign sender ID in case of unknown sender ID
                          if (receivedPacket.SenderID == NetPacket.UnknownID)
                              receivedPacket.SenderID = clientID;
  
                          // Handle received packet and forward answer packet
                          // to the client or to all other connected peers                            
                          answerPacket = HandlePacket(receivedPacket);                            
                          if (answerPacket != null)
                          {                                
                              if (answerPacket.RecipientID == clientID)
                              {
                                  // Send answer packet to the client
                                  SendPacket(client, answerPacket);
                              }
                              else
                              {
                                  // Broadcast packet to all clients
                                  foreach (TcpClient peer in _clients.Values)
                                      SendPacket(peer, answerPacket);
                              }
                          }
  
                          // Reset receive packet buffer
                          Array.Clear(buffer, 0, buffer.Length);
                          readed = 0;
                          index = 0;
                      }
                  }
              }
              catch
              {
                  System.Diagnostics.Debug.WriteLine("Network error occours!");
              }
              finally
              {
                  // Close client connection
                  client.Close();
  
                  // Remove the client from the list
                  _clients.Remove(clientID);
  
                  // Raise client disconnected event
                  OnClientDisconnected();
              }
  
          }, assignedID);
      }
  </code></pre>
  
  <p><strong>Client</strong></p>
  
  <pre><code>    public void Connect()
      {
          if (this.ConnectionAddress == null)
              throw new InvalidOperationException("Unable to connect. No server IP specified.");
  
          _receiver = new SocketAsyncEventArgs();
          _receiver.RemoteEndPoint = new IPEndPoint(this.ConnectionAddress, this.ConnectionPort);
          _receiver.SetBuffer(new byte[4096], 0, 4096);
          _receiver.Completed += new EventHandler&lt;SocketAsyncEventArgs&gt;(Socket_OperationComplete);
  
          _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            
  
          _client.ConnectAsync(_receiver);
      }
  
      private void Socket_OperationComplete(object sender, SocketAsyncEventArgs e)
      {
          if (e.SocketError == SocketError.Success)            
          {
              switch (e.LastOperation)
              {
                  case SocketAsyncOperation.Connect:
  
                      _readyToSend = true;
  
                      this.IsConnected = true;
  
                      // Once connection is estabilished, send a join packet to
                      // retrive server side assigned informations
  
                      JoinPacket joinPacket = (JoinPacket)NetPacket.CreatePacket(this.ClientID, NetPacket.ToHost, NetPacket.JoinPacket);
                      joinPacket.ClientName = this.ClientName;
                      joinPacket.ClientAddress = this.LocalAddress.ToString();
  
                      SendPacket(joinPacket);
  
                      break;
  
                  case SocketAsyncOperation.Receive:
  
                      _readyToSend = true;
  
                      byte[] buffer = _receiver.Buffer;
  
                      System.Diagnostics.Debug.WriteLine("Client received packet (" + _packetHub.GetBufferDataType(buffer) + ") with length of: " + buffer.Length);
  
                      if (_packetHub.IsValidBufferData(buffer))
                      {
                          NetPacket receivedPacket = _packetHub.DeserializePacket(buffer);
                          NetPacket answerPacket = null;
  
                          // Handle received packet and forward answer packet
                          // to the server
                          answerPacket = HandlePacket(receivedPacket);
                          if (answerPacket != null)
                              SendPacket(answerPacket);
                      }
                      else
                      {
                          _client.ReceiveAsync(_receiver);
                      }
  
                      break;
  
                  case SocketAsyncOperation.Send:                        
  
                      // Put in listen mode
                      _client.ReceiveAsync(_receiver);                        
  
                      break;
              }
          }            
          else
          {
              OnClientDisconnected();
  
              System.Diagnostics.Debug.WriteLine(String.Format("Network error: {0}", e.SocketError.ToString()));
          }
      }
  </code></pre>