代码之家  ›  专栏  ›  技术社区  ›  Jason Jarrett

如何找到空端口以启动WCF Web ServiceHost

  •  1
  • Jason Jarrett  · 技术社区  · 17 年前

    如何确定一个未使用的端口来启动wcf servicehost以承载本地主机Web服务器?

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

    我想用getunusedport()调用替换XXXX…

    有什么想法吗?

    2 回复  |  直到 17 年前
        1
  •  2
  •   Jason Jarrett    17 年前

    我能找到的最好办法就是尝试,直到你找到一个开放的选项…

    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
  •  1
  •   David Brown Muad'Dib    17 年前

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

    推荐文章