2

我继承了一个用 C# 编写的 Windows 服务 + 客户端应用程序。Windows 服务打开一个 TCP/IP 套接字进行侦听,如下所示:

socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPHostEntry iphe = Dns.Resolve(Dns.GetHostName());
socket.Bind(new IPEndPoint(iphe.AddressList[0], ExportServiceRequest.DefaultPort));
socket.Listen(2);
// Wait for incoming connections and Accept them.

而客户端连接如下:

using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
    IPHostEntry iphe = Dns.Resolve(Dns.GetHostName());
    IPEndPoint ep = new IPEndPoint(iphe.AddressList[0], ExportServiceRequest.DefaultPort);
    socket.Connect(ep);
    // Talk to the server
}

问题是在某些具有多个网络适配器的机器上,Dns.Resolve() 选择了“错误”的适配器,并且客户端连接失败。

我知道这段代码已经过时并且发臭了,并且没有编写太多原始套接字代码。是否有最好的方法来实现在套接字上侦听的 Windows 服务,以便至少本地连接(来自同一台机器内)总是成功,而不管机器有多少网络适配器?

编辑:我的问题似乎表述不当。归根结底,我希望客户端可以访问 Windows 服务,该客户端始终在同一台机器上运行,无需配置。为了拟人化,我希望 Windows 客户端只对服务器大喊:“我可以和你交谈什么 IP 地址,哦,服务在 $LOCALHOST$ 上的 TCP 端口 ExportServiceRequest.DefaultPort 上运行?我想和你交谈”,然后随后的 TCP/IP 对话正常工作。

4

1 回答 1

1

Socket.Bind

Before calling Bind, you must first create the local IPEndPoint from which you intend to communicate data. If you do not care which local address is assigned, you can create an IPEndPoint using IPAddress.Any as the address parameter, and the underlying service provider will assign the most appropriate network address. This might help simplify your application if you have multiple network interfaces.

(emphasis added). So that would be one suggested change.

I'd also suggest switching your Connect call to Connect(string,int):

Establishes a connection to a remote host. The host is specified by a host name and a port number.

(a host value of 'localhost' should be sufficient there)

That is, get rid of all of this mucking about with DNS, etc, and just rely on the underlying infrastructure to resolve these issues.

于 2012-05-09T13:29:57.970 回答