title: Connection Reset by Peer C#
body: <p>So I have windows task scheduler that runs my executable every x minutes. </p>
  
  <p>The executable does the following:</p>
  
  <ol>
  <li>See if any new messages need to sent to the server using sockets.</li>
  <li>If there are new messages then make a connection to the server
  and send each message.</li>
  <li>If there are no new messages then exit the
  executable.</li>
  </ol>
  
  <p>Problem:
  My executable does not exit and keeps running.  So the when windows task scheduler runs again it can't execute because an instance of the executable is still running.  </p>
  
  <p>The server where I sent the message told me in the error log they see this:</p>
  
  <p><strong>11-12-19 15:34:09 TCP/IP receive failed; errno 73 - Connection reset by peer.</strong></p>
  
  <p>My code:</p>
  
  <pre><code>namespace TransportMessage
  {
      class Program
      {
          static void Main(string[] args)
          {
              var systemUserId = 1
  
              try
              {
                  using (var dbContext = new DBContext())
                  {
                      var unsentRecords = dbContext.Records.Where(x =&gt; x.status == "QUEUED").ToList();
  
                      if (unsentRecords != null &amp;&amp; unsentRecords.Count &gt; 0)
                      {
                          var portNumber = 45454;
                          var dnsName = "xxxx.xxx.xxx.xxx";
  
                          IPAddress[] ipAddresses = Dns.GetHostAddresses(dnsName);
  
                          Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                          IPAddress ipAdd = System.Net.IPAddress.Parse(ipAddresses[0].ToString());
                          IPEndPoint remoteEP = new IPEndPoint(ipAdd, portNumber);
                          soc.Connect(remoteEP);
  
                          foreach (var rec in unsentRecords)
                          {
                              try
                              {
                                  byte[] byData = System.Text.Encoding.ASCII.GetBytes(rec.message_text);
                                  var numberOfBytesSent = soc.Send(byData);
  
                                  byte[] buffer = new byte[8000];
                                  int iRx = soc.Receive(buffer);
                                  char[] chars = new char[iRx];
  
                                  Decoder d = Encoding.UTF8.GetDecoder();
                                  int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
                                  string recv = new string(chars);
  
                                  rec.sent_ack_message = recv;
                                  rec.number_of_bytes_sent = numberOfBytesSent;
  
                                  var ackMessageStatus = rec.AckMessageStatus();
  
                                  if (!String.IsNullOrEmpty(ackMessageStatus))
                                  {
                                      if (ackMessageStatus == "NNN")
                                      {
                                          //Sent successfully.  NNN= Good
                                          rec.status = Status.SENT.ToString();
                                      }
                                      else
                                      {
                                          //User received anything else which means something bad in the message.
                                          rec.status = Status.FAILED.ToString();
                                          rec.last_failed_date = DateTime.Now;
                                          rec.last_failed_reason = "Message format incorrect. Please contact IT Operations. Ack Message status " + ackMessageStatus + ".";
                                      }
                                  }
                                  else
                                  {
                                      rec.status = Status.QUEUED.ToString();
                                      rec.last_failed_date = DateTime.Now;
                                      rec.last_failed_reason = "Message sent but no acknowledgment message was received. Message sent back to queued state to try again.";
                                  }
  
                                  rec.last_modified_by = systemUserId;
                                  rec.last_modified_date = DateTime.Now;
                                  rec.status_date = DateTime.Now;
                                  rec.sent_date = DateTime.Now;
                                  rec.sent_attempt_count = rec.sent_attempt_count + 1;
                                  dbContext.SaveChanges();
  
                              }
                              catch (Exception e)
                              {
                                  rec.status = Status.FAILED.ToString();
                                  rec.last_modified_by = systemUserId;
                                  rec.last_modified_date = DateTime.Now;
                                  rec.status_date = DateTime.Now;
                                  rec.last_failed_date = DateTime.Now;
                                  rec.last_failed_reason = e.ToString();
                                  rec.sent_attempt_count = rec.sent_attempt_count + 1;
                                  dbContext.SaveChanges();
                              }
                          }
                      }
                  }
              }
              catch (System.Net.Sockets.SocketException e)
              {
                  Util.LogError(LogType.FAILED_CONNECTION, e.Message, e.StackTrace);
              }
              catch (System.Data.DataException e)
              {
                  Util.LogError(LogType.FAILED_TO_CONNECT_TO_DATABASE, e.Message, e.StackTrace);
              }
              catch (Exception e)
              {
                  //General error if its not database or a socket exception issue.
                  Util.LogError(LogType.ERROR, e.Message, e.StackTrace);
              }
          }
      }
  }
  </code></pre>
  
  <p>Question:
  How do I handle when I get a connection reset by the peer?  </p>
  
  <p>I was thinking maybe after I call soc.Connect(remoteEP).  I check to see if soc.Connected is false.  If so then I disconnect.  </p>
  
  <pre><code>  if (!soc.Connected)
    {
      soc.Disconnect(true);
    }
  </code></pre>
  
  <p>Note:
  I was disconnecting the socket after I sent my messages but the admin working on the server told me not to do that.  Also the executable has been running fine for 3 weeks.  No errors or anything. </p>