15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Creating a Windows service Program ❘ 671<br />

Creating Core functionality for the service<br />

You can build any functionality in a Windows Service, such as scanning for files to do a backup or a virus<br />

check or starting a WCF server. However, all service programs share some similarities. The program must<br />

be able to start (<strong>and</strong> to return to the caller), stop, <strong>and</strong> suspend. This section looks at such an implementation<br />

using a socket server.<br />

With Windows 7, the Simple TCP/IP Services can be installed as part of the Windows components.<br />

Part of the Simple TCP/IP Services is a “quote of the day,” or qotd, TCP/IP server. This simple<br />

service listens to port 17 <strong>and</strong> answers every request with a r<strong>and</strong>om message from the file<br />

\system32\drivers\etc\quotes. With the sample service, a similar server will be built.<br />

The sample server returns a Unicode string, in contrast to the good-old qotd server that returns an<br />

ASCII string.<br />

First, create a Class Library called QuoteServer <strong>and</strong> implement the code for the server. The following<br />

walks through the source code of your QuoteServer class in the file QuoteServer.cs:<br />

using System;<br />

using System.Collections.Generic;<br />

using System.Diagnostics;<br />

using System.IO;<br />

using System.Linq;<br />

using System.Net;<br />

using System.Net.Sockets;<br />

using System.Text;<br />

using System.Threading;<br />

namespace Wrox.ProCSharp.WinServices<br />

{<br />

public class QuoteServer<br />

{<br />

private TcpListener listener;<br />

private int port;<br />

private string filename;<br />

private List quotes;<br />

private R<strong>and</strong>om r<strong>and</strong>om;<br />

private Thread listenerThread;<br />

code snippet QuoteServer/QuoteServer.cs<br />

The constructor QuoteServer() is overloaded so that a filename <strong>and</strong> a port can be passed to the<br />

call. The constructor where just the file name is passed uses the default port 7890 for the server.<br />

The default constructor defines the default filename for the quotes as quotes.txt:<br />

public QuoteServer()<br />

: this ("quotes.txt")<br />

{<br />

}<br />

public QuoteServer(string filename)<br />

: this(filename, 7890)<br />

{<br />

}<br />

public QuoteServer(string filename, int port)<br />

{<br />

this.filename = filename;<br />

this.port = port;<br />

}<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!