Question

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".

Was it helpful?

Solution

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();
}

OTHER TIPS

If you're using the "Worker Service template" in .NET Core 3.1, this might be helpful as well: https://learn.microsoft.com/en-US/aspnet/core/fundamentals/host/web-host?view=aspnetcore-3.1. Search for UseUrls. There you will find the solution, something like:

/// <summary>
/// The main method.
/// </summary>
/// <param name="args">Some arguments.</param>
public static void Main(string[] args)
{
    var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
    var pathToContentRoot = Path.GetDirectoryName(pathToExe);

    var host = WebHost.CreateDefaultBuilder(args)
        .UseContentRoot(pathToContentRoot)
        .UseStartup<Startup>()
        .UseUrls("http://*:8084")
        .Build();

    host.RunAsService();
}

should run the service as worker template with a specified port.

You can either open a socket to listen on a specific port, or configure WCF to use the given port. Ports are only required for out of process network communication.

Are you going to use sockets in your service?

If yes

        IPAddress[] localIpAddresses = Dns.GetHostAddresses(Dns.GetHostName()).Where(_ => _.AddressFamily == AddressFamily.InterNetwork).ToArray();

        //Listener
        Socket ListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        ListenerSocket.Bind(new IPEndPoint(localIpAddresses[0], Port)); //Port goes here
        ListenerSocket.Listen(100); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top