Creating a Windows Service with C#, introduction - Testing the Server
(Page 4 of 4 )
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, I’m 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.
/// </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, client.ReceiveBufferSize);
Console.WriteLine("Received response: " + Encoding.ASCII.GetString(response));
Console.ReadLine();
client.Close();
}
}
}
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.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |