title: linux service that starts an application in C# which reads from a tcp port and launch a GTK Window
body: <p>I'm coding an app for linux (ubuntu 11.04) with C# and mono. This app is a server that reads a message (an url) from a tcp port (9898) which is sent by a Client that I made. The Server receives the URL an pops up a window (gtk Window) where I embed the HTML code from the URL with WebKit. Everything works fine when I execute the program, but I need this app running at startup, so I made a shell script that is run when the computer boots up. This script executes this line "mono NetworkServer.exe &amp;". When I turn on my computer the process is alive and the NetworkServer.exe is running, but if I try to connect a Client the program crashes when it tries to create the window. If I start|restart the script manually everything works fine, so the problem is when the app is launched when the system is booting up.</p>
  
  <p>This is the script (I removed some functionality to make it simpler):</p>
  
  <pre><code>#! /bin/sh
  
  ### BEGIN INIT INFO
  # Provides:             visitord
  # Required-Start:       $local_fs $remote_fs $network
  # Required-Stop:        $local_fs $remote_fs $network
  # Default-Start:        2 3 4 5
  # Default-Stop:         0 1 6
  # Short-Description:    Create a deamon that initializes the NetworkServer.exe
  ### END INIT INFO
  
  #GLOBAL VARIABLES
  ROOT_ID=0                                   # Root ID
  USER_ID=$(id -u)                            # User ID of the user who is running the script
  PATH=/sbin:/usr/sbin:/bin:/usr/bin          # 
  APP_PATH=/usr/bin/NetworkServer.exe         # The path where the Visitor APP is located
  RETURN_VALUE=0                              # The return value
  APP_PID=`ps -ef | grep $APP_PATH | grep -v grep | awk '{print$2}'`      # The Visitor APP PID 
  
  . /lib/lsb/init-functions
  
  
  
  do_start (){
  # if it is running do nothing
  if [ -n "$APP_PID" ]; then
      echo "The visitord service is already running (pid $APP_PID)"
      RETURN_VALUE=1
  else
      if [ -f $APP_PATH ]; then
          mono $APP_PATH &amp;
          APP_PID=$!
          echo "The visitord service is running (pid $APP_PID)"
          RETURN_VALUE=0
      else
          echo "The VisitorApp doesn't exist, or its location has been changed"
          RETURN_VALUE=1
      fi
  fi
  
  }
  
  case "$1" in
    start)
      do_start
      exit $RETURN_VALUE
      ;;
    *)
      echo "Usage: visitord start|stop|restart|status" &gt;&amp;2
      exit 3
      ;;
  esac
  </code></pre>
  
  <p>This is the NetworkServer.cs code:</p>
  
  <pre><code>using System;
  using System.IO;
  using System.Net.Sockets;
  using System.Threading;
  
  namespace VisitorApp{
  
  public class NetworkServer{
  
      private int port;
      private TcpListener tcpListener;
  
      public NetworkServer(int port){
          this.port = port;
      }
  
      public  void Start(){
  
          TextWriter tw = File.AppendText("/var/www/Visitor/log.log");
  
          try{
              this.tcpListener = new TcpListener(this.port);
              this.tcpListener.Start();
              tw.WriteLine(DateTime.Now+" &gt;&gt; Server started");
          }catch{
              tw.WriteLine(DateTime.Now+" &gt;&gt; The port "+this.port+" is already in use");
              return;
          }finally{
              tw.Close(); 
          }
  
          int clientNo=0;
  
          while(true){
  
  
              System.Net.Sockets.Socket socketForClient = tcpListener.AcceptSocket();
              clientNo++;
  
              if (socketForClient.Connected){
                  tw = File.AppendText("/var/www/Visitor/log.log");
                  tw.WriteLine(DateTime.Now+" &gt;&gt; Client["+clientNo+"] is connected");
                  NetworkStream networkStream = new NetworkStream(socketForClient);
                  StreamReader streamReader = new StreamReader(networkStream);
  
                  string url;
                  try{
  
                      url = streamReader.ReadLine();
                      tw.WriteLine(DateTime.Now+" &gt;&gt; URL from the Client: "+url);
          //The execution stops here!!!!!!
                      new VisitorWindow("Visitor App",url);
                      tw.WriteLine(DateTime.Now+" &gt;&gt; An open window has been closed");
                  }catch{
                      tw.WriteLine(DateTime.Now+" The Client didn't send a URL");
  
                  }finally{
                      tw.Close();
                      socketForClient.Close();
                      networkStream.Close();
                      streamReader.Close();
                  }
  
  
              }
          }
      }
  
      public static void Main(){
  
          new Thread(new ThreadStart(
              delegate {
                  new NetworkServer(9898).Start();
              })).Start();
      }
  }
  }
  </code></pre>
  
  <p>This is the Client.cs code:</p>
  
  <pre><code>using System;
  using System.IO;
  using System.Net.Sockets;
  
  namespace Client{
  
  public class Client{
  
      private TcpClient clientSocket;
      private string server;
      private int port;
      private string url;
  
      public Client(string server, int port, string url){
          this.clientSocket = new TcpClient();
          this.server = server;
          this.port = port;
          this.url = url;
      }
  
      public void Connect(){
  
          try{
              this.clientSocket.Connect(this.server,this.port);
          }catch{
              Console.WriteLine("Unable to connect to server: "+this.server+" port: "+this.port);
              return;
          }
          NetworkStream serverStream = this.clientSocket.GetStream();
          StreamWriter streamWriter = new System.IO.StreamWriter(serverStream);
  
          try{
  
              streamWriter.WriteLine(url);
              streamWriter.Flush();
          }catch{
  
              Console.WriteLine("Exception writing to the Server");
  
          }finally{
              this.clientSocket.Close();
              serverStream.Close();
              streamWriter.Close();
          }
  
      }
  
      public static void Main(){
          Client c = new Client("localhost",9898,"http://www.stackoverflow.com");
          c.Connect();
      }
  }
  }
  </code></pre>
  
  <p>VisitorWindow.cs code:</p>
  
  <pre><code>using System;
  using System.IO;
  using Gtk;
  using WebKit;
  
  namespace VisitorApp{
  
  public class VisitorWindow {
  
      private string windowName;
      private string url;
      private Gtk.Window window;
      public TextWriter tw;
  
      public VisitorWindow(string windowName, string url){
          this.windowName = windowName;
          this.url = url;
  
          try{
              this.CreateWindow();
          }catch(Exception exc){
              this.tw.WriteLine(DateTime.Now+" &gt;&gt; "+exc.ToString());
          }finally{
              this.tw.Close();    
          }
      }
  
      public void CreateWindow(){
          this.tw = File.AppendText("/var/www/Visitor/log.log");
          this.tw.WriteLine(DateTime.Now+" &gt;&gt; Before Application.Init");
          Application.Init ();
          this.tw.WriteLine(DateTime.Now+" &gt;&gt; After Application.Init");
  
          //Set the graphical properties of the window
          this.window = new Gtk.Window (this.windowName);
          this.tw.WriteLine(DateTime.Now+" &gt;&gt; After Gtk.Window (this.windowName)");
          window.SetDefaultSize(1000,800);
          this.tw.WriteLine(DateTime.Now+" &gt;&gt; After window.SetDefaultSize(1000,800)");
          //window.FullScreen();
  
          //Adding events for actions
          window.DeleteEvent += new DeleteEventHandler (OnWindowDelete);
          this.tw.WriteLine(DateTime.Now+" &gt;&gt; After DeleteEventHandler (OnWindowDelete)");
          //Create the embed content
          ScrolledWindow scroll = new ScrolledWindow ();
          this.tw.WriteLine(DateTime.Now+" &gt;&gt; After new scroll");
  
          WebView webView = new WebView();
          this.tw.WriteLine(DateTime.Now+" &gt;&gt; After new WebView();");
  
          webView.Open (this.url);
          this.tw.WriteLine(DateTime.Now+" &gt;&gt;  webView.Open (this.url);");
          scroll.Add (webView);  
          this.tw.WriteLine(DateTime.Now+" &gt;&gt;  scroll.Add (webView);");
          window.Add (scroll);
          this.tw.WriteLine(DateTime.Now+" &gt;&gt;  window.Add (scroll);");
  
          window.ShowAll();
          this.tw.WriteLine(DateTime.Now+" &gt;&gt;  window.ShowAll()");
          Application.Run ();
          this.tw.WriteLine(DateTime.Now+" &gt;&gt;  Application.Run ");
      }
      void OnWindowDelete (object obj, DeleteEventArgs args){
          Application.Quit();
      }
  }
  }
  </code></pre>
  
  <p>Log file:</p>
  
  <pre><code>04/24/2012 08:23:27 &gt;&gt; Server started
  04/24/2012 08:24:56 &gt;&gt; Client[1] is connected
  04/24/2012 08:24:56 &gt;&gt; URL from the Client: http://www.stackoverflow.com
  </code></pre>
  
  <p>There is no error in the log file, any exception is thrown, just it crashes...
  Any help will be very useful!!</p>