Вы находитесь на странице: 1из 4

Creating a Windows Service with C#, introduction

(2006-02-28) - Contributed by David Fells

Windows Services handle a variety of tasks for your computer, usually by running quietly in the background. In this article, you will learn how to create and install a simple Windows Service. This is the first of three parts. The Zip file containing the source code for this and the other parts of this series can be found HERE.

Windows Services are applications that run in the background and perform various tasks. At any moment, your Windows PC will likely have no less than twenty running services, handling everything from TCP/IP to task scheduling. Since Windows Services are generally always on, they provide the perfect platform for applications that require persistence but do not require user interaction. Services often come with simple applications that allow you to stop, start, or pause them. Most servers, such as IIS, SQL Server, and Apache run as services.

This article will teach you how to create and install a simple Windows Service, complete with a simple Windows Form application to stop and start the service. We are going to create a simple server that accepts incoming requests on a certain TCP port, just like a web or email server. Our server will answer all requests with the current date and time string.

First we will build our server as a console application so we can debug it without having to constantly uninstall/reinstall a service. Once we have the console application built, we will create the Windows service and get it installed. Finally, we will create a service controller application that lets us stop and start the server, and register it to the system tray on the taskbar. These tasks will be seperated into three separate articles.

Creating the Console Application

Open up Visual Studio .NET (Im using the 2003 edition) and select New Project. Select Visual C# projects on the left, then scroll down to Console Application on the right. Enter the name TimeApp for your project in the box below. Click OK and wait for the project workspace to load up.

The first thing we want to do is rename Class1 to something more meaningful. Lets rename it TimeServer. To rename the file, right click the file in the solution explorer and select rename. Change the file name property to TimeServer.cs. In the class file itself, simply change class Class1 to class TimeServer. We also need to add a few namespaces to our class. We need to add System.Net and System.Net.Sockets for our network functionality, and System.Text for text encoding. Once youve added those namespaces, your class file should look like this: using System; using System.Net; using System.Net.Sockets; using System.Text; namespace TimeApp { /// <summary> /// Summary description for Class1. /// </summary> class TimeServer { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { // // TODO: Add code to start application here // } } }
http://www.aspfree.com - ASP Free Powered by Mambo Open Source Generated: 30 January, 2011, 02:47

Now its time to start writing some code!

{mospagebreak title=Creating a Listener}

Now that we have our application set up, we want to create a listener that will monitor the TCP port for incoming requests. Lets use TCP port 48888, a random, unassigned port (for a listing of TCP port assignments, go here: http://www.iana.org/assignments/port-numbers). We are going to add two readonly fields int ip = 48888 and IPAddress ip = IPAddress.Parse(127.0.0.1). These two fields are used to initialize our listener, which we will define as TcpListener listener.

In order to use these fields, we have to define a constructor, so add a public method called TimeServer() to your class file. In it, initialize the listener. Create an instance of TimeServer in the Main() method, then add a method called Start() and call it from Main Main (). Your code should look like this: using System; using System.Net; using System.Net.Sockets; using System.Text; namespace TimeApp { /// <summary> /// Summary description for Class1. /// </summary> class TimeServer { private readonly int port = 48888; private readonly IPAddress ip = IPAddress.Parse("127.0.0.1"); private TcpListener listener; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { TimeServer ts = new TimeServer(); ts.Start(); } public TimeServer() { this.listener = new TcpListener(this.ip, this.port); } public void Start() { this.listener.Start(); } } }

At this point, our application will build, but running it will not do much of anything. Next we are going to see how to handle an incoming request.

{mospagebreak title=Making the Listener Listen}

Calling listener.Start() binds the listener to the IP address and port, but that is all. We have to tell it what to do next. In
http://www.aspfree.com - ASP Free Powered by Mambo Open Source Generated: 30 January, 2011, 02:47

order to do that, we will need to create a loop. For now it will just say while (true), and to cancel the program well press ctrl + c. This will be handled a bit differently later on when we make our service. public void Start() { this.listener.Start(); while (true) { } }

Press F5 to run the application and test it. Pressing ctrl + c should terminate the program, as with any other console application. If you have a firewall installed on your PC you may get a message about this application trying to access the Internet or something similar; be sure you tell it to allow access.

Now that our listener is running and we can turn it off when were ready, we need to actually capture requests and respond to them. Capturing the request takes several steps. First, we need to create a TcpClient. Then we will use the TcpClients NetworkStream object to read into a Byte[] buffer named incomingBuffer. Once we have received the requestwhich does not get processed-we simply write back the time, in bytes, to the TcpClients NetworkStream. The code looks like this: public void Start() { this.listener.Start(); Socket s; Byte[] incomingBuffer; Byte[] time; int bytesRead; while (true) { s = this.listener.AcceptSocket(); incomingBuffer = new Byte[100]; bytesRead = s.Receive(incomingBuffer); time = Encoding.ASCII.GetBytes( System.DateTime.Now.ToString().ToCharArray()); s.Send(time); } }

{mospagebreak title=Testing the Server}

Now that we have the simple server whipped up, we need to go ahead and build it, then add a new Console Application to our TimeApp solution. Call it TimeAppTest. Rename Class1 to TimeServerTest. All this class is going to do is connect on the local port, send a request string, and output the returned time to our console. Since the code in this class is much like the code in the TimeServer class itself, Im not going to break it up and explain the parts. Here it is: using System; using System.Net; using System.Net.Sockets; using System.Text; namespace TimeAppTest { /// <summary> /// Summary description for Class1.
http://www.aspfree.com - ASP Free Powered by Mambo Open Source Generated: 30 January, 2011, 02:47

/// </summary> class TimeServerTest { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { int port = 48888; string ip = "127.0.0.1"; TcpClient client = new TcpClient(ip, port); Byte[] request = Encoding.ASCII.GetBytes("request"); Console.WriteLine("Sending request..."); client.GetStream().Write(request, 0, request.Length); Byte[] response = new Byte[client.ReceiveBufferSize]; int bytesRead = client.GetStream().Read(response, 0, Console.WriteLine("Received response: " + Console.ReadLine(); client.Close(); } } }

client.ReceiveBufferSize); Encoding.ASCII.GetString(response));

Make sure that TimeApp is set as your startup project and press F5 to run. Browse to the bin directory for the TimeAppTest project and run TimeAppTest.exe. If all goes well you will see a message that a request was received in the TimeApp server window and the current date and time string displayed in the TimeAppTest window.

Conclusion

In this article we made a simple TCP based server and a simple client application to test it. We have not looked at anything related to Windows Services-yet! But we will in the next article, where we will convert our TimeApp project to a Windows Service, install it, and use our TimeAppTest project to test it.

http://www.aspfree.com - ASP Free

Powered by Mambo Open Source

Generated: 30 January, 2011, 02:47

Вам также может понравиться