为什么我必须使用默认的 TcpClient 连接到服务器?

Why must I use default TcpClient to connect to server?

使用以下代码,我的客户端无法连接到我的服务器:

private static TcpClient client = new TcpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0));
private static IPEndPoint destinationEp = new IPEndPoint(IPAddress.Parse("192.168.0.100"), 1234);
//...
client.Connect(destinationEp);

改用 TcpClient client = new TcpClient() 即可。

原来的情况下,我的理解是,我是将本地IP设置为本地机器,使用任何可用的端口作为本地端口,以方便通信。我怀疑服务器正在尝试使用 IP“127.0.0.1”连接到客户端,这是行不通的,但我不确定。

为什么我必须使用new TcpClient()而不是new TcpClient(myEndpoint)才能成功建立服务器连接?

参见 docs:

Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.

强调我的。仅当您想控制套接字的本地部分时才使用该构造函数。另请参阅文档的其余部分:

You do not need to specify a local IP address and port number before connecting and communicating. If you create a TcpClient using any other constructor, the underlying service provider will assign the most appropriate local IP address and port number.

所以你的猜测是正确的。您基本上是在告诉网络堆栈您希望将套接字的末端绑定到 127.0.0.1:0,这不适用于出站连接。