【问题标题】:How to find empty port to start WCF web ServiceHost如何找到空端口来启动 WCF web ServiceHost
【发布时间】:2010-10-14 11:21:31
【问题描述】:

如何确定未使用的端口来启动 WCF ServiceHost 以在其上托管 localhost Web 服务器?

我目前正在http://localhost:XXXX 上静态启动我的服务,其中 XXXX 是我的代码中的静态值。

我想用 GetUnusedPort() 调用替换 XXXX...

有什么想法吗?

【问题讨论】:

    标签: c# .net wcf networking port


    【解决方案1】:

    我能找到的最好的方法是尝试直到你找到一个开放的选项......

    http://forums.devshed.com/net-development-87/c-how-to-determine-if-a-port-is-in-use-371148.html

        public static bool TryPortNumber(int port)
        {
            try
            {
    
                using (var client = new System.Net.Sockets.TcpClient(new System.Net.IPEndPoint(System.Net.IPAddress.Any, port)))
                {
                    return true;
                }
            }
            catch (System.Net.Sockets.SocketException error)
            {
                if (error.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse /* check this is the one you get */ )
                    return false;
                /* unexpected error that we DON'T have handling for here */
                throw error;
            }
        }
    

    【讨论】:

      【解决方案2】:

      为什么不让用户选择他们想在哪个端口上托管服务?例如,向应用程序的配置文件添加一个值,该文件将传递给您的 ServiceHost。您也可以尝试随机生成一个端口号并测试它是否打开,如果另一个应用程序已经在使用它,则重复该过程。

      【讨论】:

      • 各种原因。他可能正在启动一项或多项动态生成的服务,这些服务事先不知道,因此无法单独配置。
      猜你喜欢
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 2022-11-08
      相关资源
      最近更新 更多