***************This is the OnStart methd of my service*************** /// /// Set things in motion so your service can do its work. /// protected override void OnStart(string[] args) { try { quoteServer = new QuoteServer(@"C:\Temp\quotes.txt", 6500); quoteServer.Start(); // TODO: Add code here to start your service. DateTime sDate = DateTime.Now; FileStream fs = new FileStream(@"C:\Temp\arQuoteService.txt" , FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter(fs); m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); m_streamWriter.WriteLine("QuoteService OnStart: Service Started " + sDate + "\n"); m_streamWriter.Flush(); m_streamWriter.Close(); } catch(Exception e) { string message = "Quote Server failed in: " + e.Message; FileStream fs = new FileStream(@"C:\Temp\arQuoteService.txt" , FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter(fs); m_streamWriter.BaseStream.Seek(0, SeekOrigin.End); m_streamWriter.WriteLine("QuoteService OnStart: {0}\n", message); m_streamWriter.Flush(); m_streamWriter.Close(); } }
//Constructor public QuoteServer(string filename, int port) { this.filename = filename; this.port = port; } //This is the Start method that gets called from the service public void Start() { ReadQuotes(); listenerThread = new Thread(new ThreadStart(this.Listener)); listenerThread.Start(); } protected void Listener() { try { IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0]; listener = new TcpListener(ipAddress, port); listener.Start(); while (true) { Socket socket = listener.AcceptSocket(); string message = GetRandomQuoteOfTheDay(); UnicodeEncoding encoder = new UnicodeEncoding(); byte[] buffer = encoder.GetBytes(message); socket.Send(buffer, buffer.Length, 0); socket.Close(); } } catch (SocketException e) { string message = "Quote Server failed in Listener: " + e.Message; WriteToFile(message); } }