title: This TCPListener doesn't run correctly as a service
body: <p>I have extended a prooperly working program so that it can be executed as a console application as well as a service. As a console it continues to run without problems, but as a service it only runs for 5 seconds. It can be installed correctly beforehand. As soon as the service starts, it fails with the following messages.</p>
  <pre><code>Application: MessageReceiver.exe
  Framework Version: v4.0.30319
  Description: The process was terminated due to an unhandled exception.
  Exception Info: System.Net.Sockets.SocketException
     at System.Net.Sockets.Socket.DoBind(System.Net.EndPoint, System.Net.SocketAddress)
     at System.Net.Sockets.Socket.Bind(System.Net.EndPoint)
     at System.Net.Sockets.TcpListener.Start(Int32)
     at MessageReceiver.DataProcessor.Server()
     at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
     at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
     at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
     at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
     at System.Threading.ThreadHelper.ThreadStart()
  </code></pre>
  <p>It doesn't seem to be due to occupied ports and I don't see any evidence of anything on the server side that could prevent the connection. Is there some cause in the programming at hand that is preventing the program from running as a service?</p>
  <pre><code>class Program
  {
      public class DataProcessor
      {
          private static Thread n_server;
          private static Thread n_send_server;
          private static TcpClient client;
          private static TcpListener listener;
          private static Socket socket;
          private static byte[] bufferReceive = new byte[4096];
          private static byte[] bufferSend = new byte[4096];
          private static string XMLMessage;
          private static string CSVMessage;
          private static string XMLCallback;
  
          internal void Execute()
          {
              try
              {
                  n_server = new Thread(new ThreadStart(Server));
                  n_server.IsBackground = true;
                  n_server.Start();
                  Console.WriteLine(&quot;MessageReceiver started&quot;);
                  TimerTranslate.TimerTranslateStart();
              }
              catch (Exception ex)
              {
                  StreamWriter Filelog = new StreamWriter(ConfigurationManager.AppSettings.Get(&quot;logs&quot;) + &quot;\\log.txt&quot;, append: true);
                  Filelog.Write(DateTime.Now + &quot; *** &quot; + ex.Message + Environment.NewLine);
                  Filelog.Close();
              }
  
              public static void Server()
              {
                  listener = new TcpListener(IPAddress.Any, Convert.ToInt32(ConfigurationManager.AppSettings.Get(&quot;port&quot;)));
                  listener.Start();
  
                  try
                  {
                      socket = listener.AcceptSocket();
                      if (socket.Connected)
                      {
                          Console.WriteLine(&quot;Client connected on: &quot; + socket.RemoteEndPoint.ToString());
                      }
                      while (true)
                      {
                          int length = socket.Receive(bufferReceive);
                          if (length &gt; 0)
                          {
                              XMLMessage = (Encoding.UTF8.GetString(bufferReceive, 0, length));
                              Console.WriteLine(&quot;XML_Message received successfully&quot;);
                          }
                      }
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine(&quot;A client has disconnected&quot;);
  
                      StreamWriter Filelog = new StreamWriter(ConfigurationManager.AppSettings.Get(&quot;logs&quot;) + &quot;\\log.txt&quot;, append: true);
                      Filelog.Write(DateTime.Now + &quot; &quot; + ex.Message + Environment.NewLine);
                      Filelog.Close();
                  }
                  finally
                  {
                      listener.Stop();
                      n_server = new Thread(new ThreadStart(Server));
                      n_server.IsBackground = true;
                      n_server.Abort();
  
                      if (socket != null)
                      {
                          n_server = new Thread(new ThreadStart(Server));
                          n_server.IsBackground = true;
                          n_server.Start();
  
                          Console.Clear();
                          Console.WriteLine(&quot;MessageReceiver started, waitig for next connection...&quot;);
                      }
                  }
              }
  
              private static void send()
              {
                  if (socket != null)
                  {
                      bufferSend = Encoding.UTF8.GetBytes(XMLCallback);
                      socket.Send(bufferSend);
                  }
                  else
                  {
                      try
                      {
                          if (client.Connected)
                          {
                              bufferSend = Encoding.UTF8.GetBytes(XMLMessage);
                              NetworkStream nts = client.GetStream();
                              if (nts.CanWrite)
                              {
                                  nts.Write(bufferSend, 0, bufferSend.Length);
                              }
                          }
                      }
                      catch (Exception ex)
                      {
                          Console.WriteLine(&quot;Error : &quot; + ex.Message);
  
                          StreamWriter File = new StreamWriter(ConfigurationManager.AppSettings.Get(&quot;logs&quot;) + &quot;\\log.txt&quot;, append: true);
                          File.Write(DateTime.Now + &quot; *** &quot; + ex.Message + Environment.NewLine);
                          File.Close();
                      }
                      finally
                      {
                          //client.Close();                    
                      }
                  }
              }
          }
      }
  }
  </code></pre>
  <p><code>The MainClass</code></p>
  <pre><code>public class MainClass
  {
      static void Main(string[] args)
      {            
          if ((!Environment.UserInteractive))
          {
              MainClass.RunAsAService();
          }
          else
          {
              if (args != null &amp;&amp; args.Length &gt; 0)
              {
                  if (args[0].Equals(&quot;-i&quot;, StringComparison.OrdinalIgnoreCase))
                  {
                      SelfInstaller.InstallMe();
                  }
                  else
                  {
                      if (args[0].Equals(&quot;-u&quot;, StringComparison.OrdinalIgnoreCase))
                      {
                          SelfInstaller.UninstallMe();
                      }
                      else
                      {
                          Console.WriteLine(&quot;Invalid argument!&quot;);
                      }
                  }
              }
              else
              {
                  MainClass.RunAsAConsole();
              }
          }
      }
  
      static void RunAsAConsole()
      {
          DataProcessor dataProcessor = new DataProcessor();
          dataProcessor.Execute();
      }
  
      static void RunAsAService()
      {
          ServiceBase[] servicesToRun = new ServiceBase[]
          {
              new MessageReceiverService()
          };
          ServiceBase.Run(servicesToRun);
      }            
  }
  </code></pre>
  <p><code>The ServiceBase</code></p>
  <pre><code>partial class MessageReceiverService : ServiceBase
  {
      private static Timer aTimer;
  
      public MessageReceiverService()
      {
          InitializeComponent();
      }
  
      protected override void OnStart(string[] args)
      {
          aTimer = new Timer(10000); 
          aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
          aTimer.Enabled = true;
      }
  
      private static void OnTimedEvent(object source, ElapsedEventArgs e)
      {
          DataProcessor dataProcessor = new DataProcessor();
          dataProcessor.Execute();
      }
  
      protected override void OnStop()
      {
          aTimer.Stop();
      }
  }
  </code></pre>
  <p>Many thanks for help!</p>