title: TCP Socket recieves data wrong in C#
body: <p>I'm trying to send files from a Socket to another Socket. The sockets are running in two different applications, a client application and a server application. This is happening on the same machine now when testing it. The client first sends to the server when it is ready to receive first info about the file that will be sent to it like filename and file size in bytes in a 2056 bytes message. Then it sends a message each time it is ready to receive a new 2048 buffer of file content.</p>
  <p>In short, this is the communication flow for each file:</p>
  <pre><code>client -&quot;CLIENT_READY_TO_RECEIVE_FILE_INFO&quot;-------&gt; server
  client &lt;-&quot;File name+file size of file coming next&quot;-  server
  client -&quot;CLIENT_READY_TO_RECEIVE_CONTENT_BUFFER&quot; -&gt; server
  client &lt;-&quot;2048 byte buffer of file content&quot;-------- server
  ...the same flow is repeated until all files are sent to the client.
  </code></pre>
  <p>My problem is that the client receives the file info message wrong, although I have double checked that the server sends it corretly. They both use ASCII encoding. Here is my code:</p>
  <p>Client code (receives the files):</p>
  <pre><code>private void fetchFilesThreadMethod()
      {
          
  
          String localHostName = Dns.GetHostName();
          IPAddress[] localIPs = Dns.GetHostAddresses(localHostName);
          IPAddress localIP = localIPs[2];
          int port = 1305;
          IPEndPoint localEP = new IPEndPoint(localIP,port);
          fetchFilesSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
          fetchFilesSocket.Bind(localEP);
          fetchFilesSocket.Listen(1);
          fetchFilesSocket = fetchFilesSocket.Accept();
  
          while (true)
          {
              byte[] receivedFileInfo = new byte[2056];
              byte[] receivedFileCont = new byte[2048];
              byte[] comMessage = new byte[100];
              byte[] comMessageBytes;
              String fileInfoStr = String.Empty;
              String fileNameStr = String.Empty; ;
              String fileExtStr = String.Empty;
              String comMessageStr = String.Empty;
              String fileSizeStr = String.Empty;
              ulong fileSize = 0;
              ulong lastBytesSize = 0;
  
              comMessageStr = &quot;CLIENT_READY_TO_RECEIVE_FILE_INFO&quot;;
              comMessageBytes = Encoding.ASCII.GetBytes(comMessageStr);
              for (int i = 0; i &lt; comMessageBytes.Length; i++)
                  comMessage[i] = comMessageBytes[i];
              Console.WriteLine(&quot;Bytes available to be flushed by client: &quot; + fetchFilesSocket.Available);
              if (fetchFilesSocket.Available &gt; 0)
              {
                  Console.WriteLine(fetchFilesSocket.Available + &quot; bytes flushed by client.&quot;);
                  byte[] flusher = new byte[fetchFilesSocket.Available];
                  fetchFilesSocket.Receive(flusher, 0, fetchFilesSocket.Available, SocketFlags.None);
              }
              fetchFilesSocket.Send(comMessage, 0, 100, SocketFlags.None);
              Console.WriteLine(&quot;Client sent ready to receive file info.&quot;);
              fetchFilesSocket.Receive(receivedFileInfo,0,2056, SocketFlags.None);
              fileInfoStr = Encoding.ASCII.GetString(receivedFileInfo);
              Console.WriteLine(&quot;Received file info:&quot; + fileInfoStr);
              fileNameStr = fileInfoStr.Split(new String[] { &quot;ENDN&quot; }, StringSplitOptions.None)[0];
              Console.WriteLine(&quot;Received file name:&quot; + fileNameStr);
              fileExtStr = fileNameStr.Split('.').Last();
              Console.WriteLine(&quot;Received file extension:&quot; + fileExtStr);
              fileSizeStr = fileInfoStr.Split(new String[] {&quot;ENDS&quot;},StringSplitOptions.None)[0];
              fileSizeStr = fileSizeStr.Split(new String[] {&quot;ENDN&quot;},StringSplitOptions.None).Last();
              Console.WriteLine(&quot;File size string:&quot; + fileSizeStr);
              fileSize = Convert.ToUInt64(fileSizeStr,10);
              Console.WriteLine(&quot;Received file size:&quot; + fileSize);
              lastBytesSize = fileSize % 2048;
              ulong byteCount = 0;
              bool keepReceiving = true;
              ulong buffersReceived = 0;
              while (keepReceiving)
              {
                  comMessageStr = &quot;CLIENT_READY_TO_RECEIVE_CONTENT_BUFFER&quot;;
                  comMessageBytes = Encoding.ASCII.GetBytes(comMessageStr);
                  for (int i = 0; i &lt; comMessageBytes.Length; i++)
                      comMessage[i] = comMessageBytes[i];
                  fetchFilesSocket.Send(comMessage, 0, 100, SocketFlags.None);
                  Console.WriteLine(&quot;Console sent ready to receive buffer message.&quot;);
                  if (fileSize - byteCount &gt;= 2048)
                  {
                      fetchFilesSocket.Receive(receivedFileCont, 0, 2048, SocketFlags.None);
                      buffersReceived++;
                      Console.WriteLine(&quot;Buffers received:&quot; + buffersReceived);
                      byteCount = byteCount + 2048;
                  }
                  else
                  {
                      fetchFilesSocket.Receive(receivedFileCont, 0, 2048, SocketFlags.None);                        buffersReceived++;
                      byteCount = byteCount + 2048;
                      Console.WriteLine(&quot;Buffers received:&quot; + buffersReceived);
                      keepReceiving = false;
                  }
                  Console.WriteLine(&quot;Bytes received &quot; + byteCount + &quot;/&quot; + fileSize);
                  //Console.WriteLine(&quot;Received bytes in current file:&quot; + byteCount);
              }
              Console.WriteLine(&quot;File received.&quot;);
          }
      }
  </code></pre>
  <p>Server code (sends the files):</p>
  <pre><code>private void fetchThreadMethod(Object commandArgs)
      {
          if (fetchSocket == null)
          {
              fetchSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
              int port = 1304;    
              IPEndPoint fetchSocketEP = new IPEndPoint(localIP,port);
              fetchSocket.Bind(fetchSocketEP);
          }
          if (!fetchSocket.Connected)
              try
              {
                  fetchSocket.Connect(remoteIP, 1305);
                  if (fetchSocket.Connected)
                      Console.WriteLine(&quot;Server fetch socket connected.&quot;);
              }catch(Exception e)
              {
                  Console.WriteLine(&quot;Something went wrong when connecting the server fetch socket.&quot;);
              }
          FileCollector fCollector = new FileCollector();
          String userName = Environment.GetEnvironmentVariable(&quot;USERPROFILE&quot;);
          String targetDirectory = userName + &quot;\\&quot; + commandArgs;
          Console.WriteLine(&quot;Path sent to file collector:&quot; + targetDirectory);
          fCollector.startFileCollector(targetDirectory);
          List&lt;FileNode&gt; collectedFiles = fCollector.getCollectedFiles();
          String comMessageStr = String.Empty;
          foreach (FileNode fNode in collectedFiles)
          {
              comMessageStr = String.Empty;
              byte[] sentFileInfo = new byte[2056];
              byte[] sentFileCont = new byte[2048];
              byte[] comMessage = new byte[100];
              String fileName = fNode.getFileName();
              String formattedFileInfo = fileName;
              formattedFileInfo += &quot;ENDN&quot;;
              ulong fileSize = 0;
              FileStream fStream = null;
              try
              {
                  fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                  FileInfo fInfo = new FileInfo(fileName);
                  fileSize = (ulong) fInfo.Length;
                  if (fileSize == 0)
                      continue;
                  formattedFileInfo += fileSize.ToString() + &quot;ENDS&quot;;
              }
              catch (Exception e)
              {
                  Console.WriteLine(&quot;Could not read from file:&quot; + fileName);
                  deniedAccessFiles.Add(fileName);
                  continue;
              }
              byte[] fileInfoBytes = Encoding.ASCII.GetBytes(formattedFileInfo);
              for (int i = 0; i &lt; fileInfoBytes.Length; i++)
                  sentFileInfo[i] = fileInfoBytes[i];
              while (!comMessageStr.Equals(&quot;CLIENT_READY_TO_RECEIVE_FILE_INFO&quot;))
              {
                  Console.WriteLine(&quot;Server waiting for file info ready message from client.&quot;);
                  fetchSocket.Receive(comMessage,0,100,SocketFlags.None);
                  comMessageStr = Encoding.ASCII.GetString(comMessage);
                  comMessageStr = comMessageStr.Substring(0,33);
                  Console.WriteLine(&quot;Received parsed message from client:&quot; + comMessageStr);
              }
              Console.WriteLine(&quot;Server received file info ready message from client.&quot;);
              comMessageStr = String.Empty;
              Console.WriteLine(&quot;formattedFileInfo:&quot; + formattedFileInfo);
              Console.WriteLine(&quot;Sent file info:&quot; + Encoding.ASCII.GetString(sentFileInfo));
              fetchSocket.Send(sentFileInfo, 0, 2056, SocketFlags.None);
              int readByte = 0;
              ulong byteCount = 0;
              ulong buffersSent = 0;
              while (readByte != -1)
              {
                  if (byteCount == 2048)
                  {
                      while (!comMessageStr.Equals(&quot;CLIENT_READY_TO_RECEIVE_CONTENT_BUFFER&quot;))
                      {
                          Console.WriteLine(&quot;Server waiting for ready for buffer message from client.&quot;);
                          fetchSocket.Receive(comMessage, 100, SocketFlags.None);
                          comMessageStr = Encoding.ASCII.GetString(comMessage);
                          comMessageStr = comMessageStr.Substring(0,38);
                          Console.WriteLine(&quot;Received parsed message from client 1:&quot; + comMessageStr);
                      }
                      Console.WriteLine(&quot;Server received ready for buffer message from client.&quot;);
                      fetchSocket.Send(sentFileCont, 0, 2048, SocketFlags.None);
                      comMessageStr = String.Empty;
                      buffersSent++;
                      Console.WriteLine(&quot;Buffers sent:&quot; + buffersSent);
                      byteCount = 0;
                  }
                  else
                  {
                      readByte = fStream.ReadByte();
                      if (readByte != -1)
                      {
                          sentFileCont[byteCount] = Convert.ToByte(readByte);
                          byteCount++;
                      }
                  }   
              }
              while (!comMessageStr.Equals(&quot;CLIENT_READY_TO_RECEIVE_CONTENT_BUFFER&quot;))
              {
                  Console.WriteLine(&quot;Server waiting for ready for buffer message from client.&quot;);
                  fetchSocket.Receive(comMessage, 100, SocketFlags.None);
                  comMessageStr = Encoding.ASCII.GetString(comMessage);
                  comMessageStr = comMessageStr.Substring(0, 38);
                  Console.WriteLine(&quot;Received parsed message from client 2:&quot; + comMessageStr);
              }
              Console.WriteLine(&quot;Server received ready for buffer message from client.&quot;);
              fetchSocket.Send(sentFileCont, 0, 2048, SocketFlags.None);
              buffersSent++;
              Console.WriteLine(&quot;Buffers sent:&quot; + buffersSent);
              comMessageStr = String.Empty;  
          }
      }
  </code></pre>
  <p>Console outputs:
  <a href="https://i.stack.imgur.com/smnEY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/smnEY.png" alt="enter image description here" /></a></p>