public async Task <ConnectResult> ConnectToServer(string host, int port) { IPAddress ip; if (!IPAddress.TryParse(host, out ip)) { var addressList = Dns.GetHostEntry(host).AddressList; var ipv4Addresses = Array.FindAll(addressList, a => a.AddressFamily == AddressFamily.InterNetwork); if (ipv4Addresses.Length == 0) { return(ConnectResult.InvalidEndpoint); } ip = ipv4Addresses[0]; } var endPoint = new IPEndPoint(ip, port); using (var cts = new CancellationTokenSource(5000)) { var task = _socket.ConnectAsync(endPoint, cts.Token); await task; return(task.IsCanceled ? ConnectResult.Timeout : task.Result); } }
private static void SetupConnectAsync(IAsyncSocket socket) { var awaitable = Substitute.For <ISocketAwaitable <bool> >(); awaitable.GetAwaiter().Returns(awaitable); awaitable.IsCompleted.Returns(true); awaitable.GetResult().Returns(true); socket.ConnectAsync().Returns(awaitable); }