用的是 .net core 2.1 ,linux 版本是 ubuntu 16.04,连接 socket 的代码如下:
private void ConnectWithTimeout(Socket socket, DnsEndPoint endpoint, int timeout)
{
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
var args = new SocketAsyncEventArgs();
args.RemoteEndPoint = endpoint;
using (var mres = new ManualResetEventSlim())
{
args.Completed += (s, e) => mres.Set();
if (socket.ConnectAsync(args))
{
if(!mres.Wait(timeout))
{
throw new TimeoutException("Could not connect to " + endpoint);
}
}
}
}
运行时报错:
System.PlatformNotSupportedException: Sockets on this platform are invalid for use after a failed connection attempt.
at System.Net.Sockets.Socket.ThrowMultiConnectNotSupported()
at System.Net.Sockets.Socket.ConnectAsync(SocketAsyncEventArgs e)
请问如何解决?
连接 socket 时使用主机名(不是IP)并且启用 KeepAlive 时会触发这个问题,github 上有人向 corefx 提交过 issue ,详见 PlatformNotSupportedException with TcpClient.ConnectAsync