问题
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:
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();
}
回答2:
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.
回答3:
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);
来源:https://stackoverflow.com/questions/22389620/set-the-port-number-in-windows-service