/// <summary> /// Disconnects any open connection to a terminal. /// </summary> public void Disconnect() { try { if (!Connected) { Util.Log("Already disconnected.", _remoteEndPoint.Address); return; } _socket.Disconnect(false); Util.Log("Disconnected.", _remoteEndPoint.Address); } catch { // Swallow any exceptions. The socket is probably closed. } finally { // Exit the gatekeeper if (_useGateKeeper) { GateKeeper.Exit(_remoteEndPoint); } } }
public static async Task <NetworkConnection> ConnectAsync(IPEndPoint endPoint, TimeSpan timeout = default(TimeSpan)) { Util.Log("Connecting to terminal...", endPoint.Address); // default timeout is five seconds if (timeout <= TimeSpan.Zero) { timeout = TimeSpan.FromSeconds(5); } // Enter the gate. This will block until it is safe to connect. await GateKeeper.EnterAsync(endPoint, timeout); // Now we can try to connect, using the specified timeout. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var connectTask = Task.Factory.FromAsync( (ep, callback, state) => { try { return(socket.BeginConnect(ep, callback, state)); } catch { GateKeeper.Exit(ep); throw; } }, ar => { try { socket.EndConnect(ar); } catch { // Swallow any exceptions. The socket is probably closed. } }, endPoint, null); await TaskEx.WhenAny(connectTask, TaskEx.Delay(timeout)); if (!socket.Connected) { socket.Close(); GateKeeper.Exit(endPoint); throw new TimeoutException("Timeout occurred while trying to connect to the terminal."); } Util.Log("Connected!", endPoint.Address); return(new NetworkConnection(socket, true)); }
public static NetworkConnection Connect(IPEndPoint endPoint, TimeSpan timeout = default(TimeSpan)) { Util.Log("Connecting to terminal...", endPoint.Address); // default timeout is five seconds if (timeout <= TimeSpan.Zero) { timeout = TimeSpan.FromSeconds(5); } // Enter the gate. This will block until it is safe to connect. GateKeeper.Enter(endPoint, timeout); var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { // Now we can try to connect, using the specified timeout. var result = socket.BeginConnect(endPoint, ar => { try { socket.EndConnect(ar); } catch { // Swallow any exceptions. The socket is probably closed. } }, null); result.AsyncWaitHandle.WaitOne(timeout, true); if (!socket.Connected) { socket.Close(); GateKeeper.Exit(endPoint); throw new TimeoutException("Timeout occurred while trying to connect to the terminal."); } } catch { // just in case GateKeeper.Exit(endPoint); throw; } Util.Log("Connected!", endPoint.Address); return(new NetworkConnection(socket, true)); }