title: C# Multithreading Clients Duplicate Connection/Data Loss
body: <p>I am having a weird problem where I am making a chat connection with TCPListeners and sockets. For some reason when a client "connects" to the server it will show they have connected twice. Also what is weird once all of the users have connected I will send out a message to all of them. They will respond back with it acknowledged and state that their chat has started.</p>
  
  <p>Things I am noticing with how i have it setup:</p>
  
  <ol>
  <li>It appears according to the log that the user "connects" twice the second "connect occurs once it hits the white(true) loop.</li>
  <li>When they send over the acknowledgement back to the server not all of the data is getting sent over. If I do a thread sleep on the client it does appear to start working but it is still inconsistent.</li>
  </ol>
  
  <p>Here is the code:</p>
  
  <p><strong>Server:</strong></p>
  
  <pre><code>private TcpListener tcpListener;
  private Thread listen;
  private TcpListener tcpUser1, tcpUser2,tcpUser3;
  NetworkStream User1Stream,User2Stream,User3Stream;
  public event NetworkMessageStringDelegate MessageFromUser;
  TcpClient client;
  
  public void start(string ip){
  
      IpHostEntry host = dns.GetHostEntry(dns.GetHostName());
      IpAddress[] ip = host.AddressList;
      serverStatus = "Server started with IP of: " + ip;
      Thread.Sleep(1);
  
      tcpUser1 = new TcpListener(IpAddress.Any, 4001);
      listen = new Thread(new ThreadStart(() =&gt; ListenUser1(tcpUser1)));
      listen.Start();
      Thread.Sleep(1);
  
      tcpUser2 = new TcpListener(IpAddress.Any, 4002);
      listen = new Thread(new ThreadStart(() =&gt; ListenUser2(tcpUser2)));
      listen.Start();
      Thread.Sleep(1);
  
      tcpUser3 = new TcpListener(IpAddress.Any, 4003);
      listen = new Thread(new ThreadStart(() =&gt; ListenUser3(tcpUser3)));
      listen.Start();
      Thread.Sleep(1);
  
  }
  
  public void ListenUser3(TcpListener tmp){
  
      tcpListener = (TcpListener)tmp;
      Socket = "Listening for User3";
      tcpUser3.Start();
  
      Thread.Sleep(2);
  
      while(true){
          user3 = this.tcpListener.AcceptTcpClient();
          Thread user3Thread = new Thread(new ParmeterizedThreadStart(receiveUser3Data));
          user3Thread.Start(user3);
      }
  }
  
  //Mostly from MS documenation
  private void receiveUser3Data(object client){
      client = (TcpClient)client;
      User3Stream = client.getStream();
      Socket = "Connected to User: " + client.Client.RemoteEndPoint.toString();
      byte[] message = new byte[4096];
      int total;
  
      //This is the line it will display the socket message Twice. "Connected to User...."
      while(true){
          total = 0;
          try{
              do{
                  total = User3Stream.Read(message,0,4096);
              }
              while(user3.DataAvailable);
          }
          catch()
          {
              Socket = "Error State";
          }
      }
      byte[] infoPacket = new byte[total];
      Array.ConstrainedCopy(message,0,infoPacket,total);
      if(MessageFromUser3 != null){
          MessageFromUser?.Invoke(packet);
      }
  }
  </code></pre>
  
  <p><strong>Client:</strong></p>
  
  <pre><code>public void ConfigureUser3(){
  
      try{
          socket = new Network.TCPIPClient();
          socket.ReceiveMessage() = new Newowrk.TCPIPClient.NetworkMessageStringDelgate(MessageFromserver);
          socket.SendMessage() = new Newowrk.TCPIPClient.NetworkMessageStringDelgate(sendMessage);
          userThread = new Thread(() =&gt; socket.Start("0.0.0.0),4054));
          userThread.Start();
      }
      catch(Exception ex){
  
      }
  }
  
  //This is where if I sleep it will send but it is still inconsident
  private void SendMEssageToSever(object tmpVal){
      object[] sendMessage = tmpVal as object[];
      string tmpSendValue  = tmpVal[0].ToString();
      byte sendValue = Coonvert.ToByte(tmpVal[1]);
      packetData[0] = 0;
      packetData[1] = sendValue;
      packetData[2] = Convert.ToByte(tmpSendValue);
  
      socket.sendMessage = packetData;
  }
  
  private voide sendMessage(byte[] userMessage){
      try{
          if(socket){
              outputMessage.Enqueue(userMessage);
              while(outputMessage.Count &gt; 0){
                  Byte[] sendMessage = outputMessage.Dequeue();
                  string message = ascII.GetString(sendMessage);
                  if(socket.Connected){
                      lock(socket){
                          socket.Send(sendMessage,sendMessage.length,0);
                      }
                  }
              }
          }
      }
      catch(Exception ex)
  }
  </code></pre>
  
  <p>This code is essentially repeated for all users that are connected to the server.</p>