C#异步网络连接的问题

2023/03 30 19:03

以下代码,正常情况下,一切工作正常,可以打印出ConnectComplete

var mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
mSocket.NoDelay = true;
mSocket.Blocking = false;
mSocket.LingerState = new LingerOption(true, 0);
IPEndPoint point = new IPEndPoint(ipAddress, port);
var asyncEvtArgs = new SocketAsyncEventArgs();
asyncEvtArgs.RemoteEndPoint = point;
asyncEvtArgs.Completed += OnConnectedCompleted;
mSocket.ConnectAsync(asyncEvtArgs);

...

void OnConnectedCompleted(object sender, SocketAsyncEventArgs args)
{
  Debug.Log("ConnectComplete")
}

但是在Android平台上,在游戏内,下拉控制台,点Wifi图标关闭网络,再去连接,则 无法打印出 ConnectComplete,即回调无反应


解决方案为当调用ConnectAsync时,添加一个超时定时器