title: C# An existing connection was forcibly closed by the remote host: socket programming
body: <p>I am working with sockets. Here are my codes (the description of problem is further):</p>
  
  <p><strong>Client side</strong>:</p>
  
  <pre><code>    public void ReadCallback(IAsyncResult ar)
      {
          int fileNameLen = 1;
          String content = String.Empty;
          StateObject state = (StateObject)ar.AsyncState;
          Socket handler = state.workSocket;
  
          int bytesRead = handler.EndReceive(ar);
          if (bytesRead &gt; 0)
          {
  
              if (flag == 0)
              {
  
                  fileNameLen = BitConverter.ToInt32(state.buffer, 0);
                  string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
                  receivedPath = mypath + @"XML\";
                  if (!Directory.Exists(receivedPath))
                  {
                      Directory.CreateDirectory(receivedPath);
                  }
                  receivedPath = receivedPath + fileName;
                  flag++;
  
              }
              if (flag &gt;= 1)
              {
  
                  BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
                  if (flag == 1)
                  {
                      writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
                      flag++;
                  }
                  else
                      writer.Write(state.buffer, 0, bytesRead);
                  writer.Close();
                  handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                  new AsyncCallback(ReadCallback), state);
              }
  
          }
          else
          {
              //   Invoke(new MyDelegate(LabelWriter));
          }
      }
  </code></pre>
  
  <p>I get error on this line: <code>int bytesRead = handler.EndReceive(ar);</code></p>
  
  <p>How can I avoid this error?: <code>An existing connection was forcibly closed by the remote host</code></p>
  
  <p><strong>Server side</strong>:</p>
  
  <pre><code>        public void ReadCallback(IAsyncResult ar)
          {
              try
              {
  
                  int fileNameLen = 1;
                  String content = String.Empty;
                  StateObject state = (StateObject)ar.AsyncState;
                  Socket handler = state.workSocket;
                  string[] str = new string[2];
                  str = handler.RemoteEndPoint.ToString().Split(':');
                  IP = str[0].ToString();
                  int bytesRead = handler.EndReceive(ar);
  
                  if (bytesRead &gt; 0)
                  {
                      if (flag == 0)
                      {
                          fileNameLen = BitConverter.ToInt32(state.buffer, 0);
                          string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
                          string[] getIP = new string[3];
                          getIP = fileName.Split('_');
                          #region Send Files in HandHeld
                          #region GetLoginFile
                          if (getIP[1].ToString().Equals("GetLoginFile"))
                          {
                              string getDirectory = @"Send_Hand_Held_Files\" + DateTime.Today.ToString("dd-MM-yyyy") + "\\" + getIP[0].ToString() + "\\XML";
                              string strmyFile = getDirectory + "\\Login.xml";
                              char[] delimiter = splitter.ToCharArray();
                              split = strmyFile.Split(delimiter);
                              int limit = split.Length;
                              fName = split[limit - 1].ToString();
  
                              byte[] LoginfileName = Encoding.UTF8.GetBytes(fName); //file name
  
                              byte[] fileData = File.ReadAllBytes(strmyFile);
  
                              byte[] LoginfileNameLen = BitConverter.GetBytes(LoginfileName.Length); //lenght of file name
                              clientData = new byte[4 + LoginfileName.Length + fileData.Length];
  
                              LoginfileNameLen.CopyTo(clientData, 0);
                              LoginfileName.CopyTo(clientData, 4);
                              fileData.CopyTo(clientData, 4 + LoginfileName.Length);
  
                              handler.BeginSend(clientData, 0, clientData.Length, 0, new AsyncCallback(SendCallBack), handler);
                              //handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                              //new AsyncCallback(ReadCallback), state);
                              return;
                          }
   }
              catch (Exception ex)
              {
                  MessageBox.Show(ex.Message);
  
              }
              //SendData(IP);
          }
  
       private static void SendCallBack(IAsyncResult ar)
          {
              try
              {
                  // Retrieve the socket from the state object.
                  Socket client = (Socket)ar.AsyncState;
  
                  // Complete sending the data to the remote device.
                 // int bytesSent = client.EndSend(ar);
                  //Console.WriteLine("Sent {0} bytes to server.", bytesSent);
  
                  // Signal that all bytes have been sent.
                  allDone.Set();
  
              }
              catch (Exception e)
              {
                  Console.WriteLine(e.ToString());
              }
          }
  </code></pre>