1

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

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

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

有什么想法吗?

4

2 回答 2

2

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

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;
        }
    }
于 2009-03-22T01:39:28.223 回答
1

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

于 2009-03-20T03:45:51.260 回答