title: C# TCP server sometimes send string containing parts of last message
body: <p>I am working on my project in which i need arduinos to comunicate with my TCP server app. Eveyrthing was going fine as of now. But i just noticed that the server sometimes send invalid string to the client. (the string simply contains parts of the last string sent) Those the arduino doesnt know what to do with it.</p>
  <p>How it should work:</p>
  <p>Server receives: &quot;CNN:1&quot; (connection request from arduino #1)</p>
  <p>Server sends: &quot;CNN:1:CFM&quot; (confirming that the request was recieved.</p>
  <p>Server Recieves: &quot;PING&quot;</p>
  <p>Server Sends: &quot;PONG&quot;</p>
  <p>Server Recieves: &quot;CHGTM:1:B&quot; (arduino #1 sends request to change team to Blue)</p>
  <p>Server Sends: &quot;CHGTM:1:B:CFM&quot; or &quot;CHGTM:1:GMPAUSED&quot; (depends on wheter the game is running or is paused)</p>
  <p>EXAMPLE OF THE BAD BEHAVIOUR:</p>
  <p>Server Recieves: &quot;CNN:1&quot;</p>
  <p>sends: &quot;CNN:1:CFM&quot;</p>
  <p>Recieves: &quot;PING&quot;</p>
  <p>Sends: &quot;PONG1:CFM&quot;  (This message contains part of the last message those is corrupted -- It doesnt happen everytime only sometimes)</p>
  <p>Do anybody know how to fix this? I tried nulling the string variables used to contain the text before sending but no luck. I also tried flushing the networkstream after writing to it but also no luck (as i understand it, this method is just placeholder and doesnt do anything at the moment)</p>
  <p>Here is the code that i am using for the communication:</p>
  <pre><code>    class Comunication
  {
      TcpListener server = null;
      public List&lt;Majak&gt; activeClients;
      public MainWindow mw { get; set; }
      public bool isConOk { get; set; }
      public Comunication(string ip, int port, MainWindow _mw)
      {
          mw = _mw;
          activeClients = new List&lt;Majak&gt;();
          IPAddress localAddr = IPAddress.Parse(ip);
          server = new TcpListener(localAddr, port);
          server.Start();
          StartConnectionCheck();
          StartListener();
          //StartConnectionCheck();
      }
      public void StartListener()
      {
          try
          {
              while (true)
              {
                  TcpClient client = server.AcceptTcpClient();
                  if(client != null)
                  {
                      Majak m = new Majak(client);
  
                      Thread t = new Thread(new ParameterizedThreadStart(HandleDevice));
                      t.Start(m);
                      activeClients.Add(m);
                  }
              }
          }
          catch(SocketException e)
          {
              MessageBox.Show(&quot;Nelze spustit server&quot;, e.ToString());
              server.Stop();
          }
      }
      public void HandleDevice(Object obj)
      {
          Majak majak = (Majak)obj;
          if (majak != null &amp;&amp; majak.isConnected)
          {
              var stream = majak.Client.GetStream();
              string imei = String.Empty;
  
              string data = null;
              Byte[] bytes = new Byte[256];
              int i;
  
              try
              {
                  while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                  {
                      string hex = BitConverter.ToString(bytes);
                      data = Encoding.ASCII.GetString(bytes, 0, i); //text revieved from arduino needs evaluation
                      DataEvaluation(data, majak);
                  }
              }
              catch (Exception e) //if there is an error than the client is closed and removed from list of connected clients and this thread is stopped
              {
                  //MessageBox.Show(e.ToString(), &quot;Chyba při komunikaci s majákem&quot;);
                  App.Current.Dispatcher.Invoke((Action)delegate // &lt;--- HERE
                  {
                      activeClients.Remove(majak);
                  });
                  majak.isConnected = false;
                  majak.Client.Close();
                  return;
              }
          }
      }
      public void DataEvaluation(string d, Majak m)
      {
          //split data by &quot;:&quot;
          string[] datasplt = d.Split(':');
          switch(datasplt[0]){
              case &quot;CNN&quot;:
                  m.ID = int.Parse(datasplt[1]);
                  SendResponse(1, m);
                  break;
              case &quot;PONG&quot;:
                  isConOk = true;
                  break;
              case &quot;PING&quot;:
                  SendResponse(3, m);
                  break;
              case &quot;CHGTM&quot;:
                  m.Color = datasplt[2];
                  if(mw.SS.ChangeTeam(int.Parse(datasplt[1]), datasplt[2]))
                  {
                      SendResponse(2, m); //if the game is running than sends confirmation to the arduino
                  }
                  else
                  {
                      SendResponse(4, m); //if the game is paused sends to arduino string saying so
                  }
                  break;
          }
      }
      public void SendResponse(int i, Majak m) 
      {
          string response = null;
          Byte[] response_byte = null;
          switch (i)
          {
              case 1: //connection cofirmation
                  //connection validation
                  response = null;
                  response = string.Format(&quot;CNN:{0}:CFM&quot;, m.ID);
                  response_byte = null;
                  response_byte = System.Text.Encoding.ASCII.GetBytes(response);
                  try
                  {
                      m.Client.GetStream().Write(response_byte, 0, response_byte.Length);
                      m.Client.GetStream().Flush();
                  }
                  catch { }
                  break;
              case 2: //change team confirmation
                  //confirms change of team
                  response = null;
                  response = string.Format(&quot;CHGTM:{0}:{1}:CFM&quot;, m.ID, m.Color);
                  response_byte = null;
                  response_byte = System.Text.Encoding.ASCII.GetBytes(response);
                  try
                  {
                      m.Client.GetStream().Write(response_byte, 0, response_byte.Length);
                      m.Client.GetStream().Flush();
                  }
                  catch { }
                  break;
              case 3: //Sends PONG if PING is recieved
                  response = null;
                  response = &quot;PONG&quot;;
                  response_byte = null;
                  response_byte = System.Text.Encoding.ASCII.GetBytes(response);
                  try
                  {
                      m.Client.GetStream().Write(response_byte, 0, response_byte.Length);
                      m.Client.GetStream().Flush();
                  }
                  catch { }
                  break;
              case 4:
                  response = null;
                  response = string.Format(&quot;CHGTM:{0}:GMPAUSED&quot;, m.ID);
                  response_byte = null;
                  response_byte = System.Text.Encoding.ASCII.GetBytes(response);
                  try
                  {
                      m.Client.GetStream().Write(response_byte, 0, response_byte.Length);
                      m.Client.GetStream().Flush();
                  }
                  catch { }
                  break;
          }
      }
      public void StartConnectionCheck()
      {
          Thread t = new Thread(new ParameterizedThreadStart(CheckConnectionStatus));
          t.Start(mw);
      }
      public void CheckConnectionStatus(Object __mw) //every 30 seconds sends PING to the arduino in order to evaluate if the connection still exists. If the PONG is not recieved in 30 seconds than closes connection and remove client from connected clients
      {
          while (true)
          {
                  string pingmsg = &quot;PING&quot;;
                  Byte[] pingmsg_byte = System.Text.Encoding.ASCII.GetBytes(pingmsg);
                  Stopwatch s = new Stopwatch();
  
              foreach (Majak m in activeClients.ToList&lt;Majak&gt;())
              {
                  isConOk = false;
                  var stream = m.Client.GetStream();
                  Byte[] bytes = new Byte[256];
  
                  try
                  {
                      stream.Write(pingmsg_byte, 0, pingmsg_byte.Length);
                      s.Restart();
                      while (s.Elapsed &lt; TimeSpan.FromSeconds(30) &amp;&amp; !isConOk)
                      {
  
                      }
                      if (!isConOk)
                      {
                          m.isConnected = false;
                          activeClients.Remove(m);
                          m.Client.GetStream().Close();
                          m.Client.Close();
                      }
                  }
                  catch (Exception e)
                  {
                      m.isConnected = false;
                      activeClients.Remove(m);
                      m.Client.Close();
                  }
              }
              
              Thread.Sleep(30000);
          }
      }
  }
  </code></pre>