user1108948
user1108948

Reputation:

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

Upvotes: 4

Views: 13602

Answers (4)

FranzHuber23
FranzHuber23

Reputation: 4252

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.

Upvotes: 1

Cam Bruce
Cam Bruce

Reputation: 5689

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

Upvotes: 4

SirH
SirH

Reputation: 575

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

Upvotes: 0

Haney
Haney

Reputation: 34762

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.

Upvotes: 0

Related Questions