Set the port number in windows service

試著忘記壹切 提交于 2019-12-24 03:04:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!