Creating a Windows Service with C#, introduction - Creating a Listener
(Page 2 of 4 )
Now that we have our application set up, we want to create a listener that will monitor the TCP port for incoming requests. Let’s 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.
Next: Making the Listener Listen >>
More C# Articles
More By David Fells