我在跨平台 C# 应用程序 (Avalonia/Xamarin) 中尝试连接 TCP 套接字时遇到超时 - 但行为非常奇怪:
System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (110): Connection timed out
连接代码很简单:
public void Connect(string host, int port)
{
IPAddress ipAddress;
IPAddress.TryParse(host, out ipAddress);
IPEndPoint ipe = new IPEndPoint(ipAddress, port);
try
{
_tcpSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// On Android, it pauses here for a bit & then times out/throws
_tcpSocket.Connect(ipe);
}
}
为什么这段代码能够连接 Windows->Hardware、Windows->ServerSimulator、Android->ServerSimulator...但在 Android->Hardware 上却超时?
解决了。问题是,如果 Android 设备有另一个互联网连接,则无法解析 IP;如果你将其设置为飞行模式并连接到 WiFi 网络,它就可以工作。由于手机通过 SIM 卡上网,而模拟器通过主机 PC 连接上网,所以都失败了。