Creating a Windows Service with C#, introduction - Making the Listener Listen
(Page 3 of 4 )
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 order to do that, we will need to create a loop. For now it will just say “while (true)”, and to cancel the program we’ll 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 we’re 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 TcpClient’s NetworkStream object to read into a Byte[] buffer named incomingBuffer. Once we have received the request-–which does not get processed-–we simply write back the time, in bytes, to the TcpClient’s 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);
}
}
Next: Testing the Server >>
More C# Articles
More By David Fells