Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the port number in windows service

I am going to develop a windows service. When the service starts, there is a port with it. My question is that can we assign a specific port number to it? Example, port number is "55431".


1 Answers

Yes. Assuming you're using WCF as the communication layer, you would just configure the binding/protocol to listen to as part of the service configuration. In your service's OnStart() method you would register the port. You would un-register it, when the service stops.

Complete Walk-Through

protected override void OnStart(string[] args)
{
// Configure a binding on a TCP port
NetTcpBinding binding = new NetTcpBinding();

ServiceHost host = new ServiceHost(typeof(MyService));

string address = "net.tcp://localhost:55431/myservice"

host.AddServiceEndpoint(typeof(IMyService), binding, address);
host.Open();
}
like image 186
Cam Bruce Avatar answered Nov 02 '25 09:11

Cam Bruce