【发布时间】:2010-10-14 11:21:31
【问题描述】:
如何确定未使用的端口来启动 WCF ServiceHost 以在其上托管 localhost Web 服务器?
我目前正在http://localhost:XXXX 上静态启动我的服务,其中 XXXX 是我的代码中的静态值。
我想用 GetUnusedPort() 调用替换 XXXX...
有什么想法吗?
【问题讨论】:
标签: c# .net wcf networking port
如何确定未使用的端口来启动 WCF ServiceHost 以在其上托管 localhost Web 服务器?
我目前正在http://localhost:XXXX 上静态启动我的服务,其中 XXXX 是我的代码中的静态值。
我想用 GetUnusedPort() 调用替换 XXXX...
有什么想法吗?
【问题讨论】:
标签: c# .net wcf networking port
我能找到的最好的方法是尝试直到你找到一个开放的选项......
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;
}
}
【讨论】:
为什么不让用户选择他们想在哪个端口上托管服务?例如,向应用程序的配置文件添加一个值,该文件将传递给您的 ServiceHost。您也可以尝试随机生成一个端口号并测试它是否打开,如果另一个应用程序已经在使用它,则重复该过程。
【讨论】: