//------------------------------------------------------------------------------ // // Method: Disconnect // //------------------------------------------------------------------------------ /// <summary> /// Disconnects from the configured IP address and port. /// </summary> public void Disconnect() { CheckNotDisposed(); if (client.Connected == true) { client.Close(); loggingUtilities.Log(this, LogLevel.Information, "Disconnected."); } }
public void Dispose() { _cancellationTokenSource.Cancel(); _client.Close(); lock (_syncQueue) Monitor.Pulse(_syncQueue); _sendThread.Wait(); _cancellationTokenSource.Dispose(); _sendqueue = new ConcurrentQueue <Tuple <byte[], int, int> >(); }
private void Connect(ITcpClient socket, AmqpTcpEndpoint endpoint, int timeout) { IAsyncResult ar = null; try { ar = socket.BeginConnect(endpoint.HostName, endpoint.Port, null, null); if (!ar.AsyncWaitHandle.WaitOne(timeout, false)) { socket.Close(); throw new TimeoutException("Connection to " + endpoint + " timed out"); } socket.EndConnect(ar); } catch (ArgumentException e) { throw new ConnectFailureException("Connection failed", e); } catch (SocketException e) { throw new ConnectFailureException("Connection failed", e); } finally { if (ar != null) { ar.AsyncWaitHandle.Close(); } } }
private void ReturnClient(ITcpClient client) { try { if (statusCode == 200 && client.Connected && GetResponseHeader("Connection") != "close" && string.IsNullOrEmpty(_error)) { lock (connections) { List <ITcpClient> clients = null; if (!connections.TryGetValue(connectionKey, out clients)) { clients = new List <ITcpClient>(); connections[connectionKey] = clients; } clients.Add(client); } } else { // dispose client.Close(); } } catch { } }
/// <summary> /// Closes the transport. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> protected override Task PerformCloseAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); _stream?.Close(); _tcpClient.Close(); return(_envelopePipe.StopAsync(cancellationToken)); }
public void Close() { lock (_semaphore) { if (!_closed) { try { _frameChannel.Writer.Complete(); _frameWriter.Wait(); } catch (Exception) { } try { _socket.Close(); } catch (Exception) { // ignore, we are closing anyway } finally { _closed = true; } } } }
/// <summary> /// Closes the transport. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> protected override Task PerformCloseAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); _stream?.Close(); _tcpClient.Close(); return(Task.FromResult <object>(null)); }
public void Close() { lock (_semaphore) { if (!_closed) { try { try { } catch (ArgumentException) { // ignore, we are closing anyway }; m_socket.Close(); } catch (Exception) { // ignore, we are closing anyway } finally { _closed = true; } } } }
public void Close() { lock (_semaphore) { if (_closed || _socket == null) { return; } else { try { _channelWriter.Complete(); _writerTask?.GetAwaiter().GetResult(); } catch { // ignore, we are closing anyway } try { _socket.Close(); } catch { // ignore, we are closing anyway } finally { _closed = true; } } } }
public void Close() { lock (_semaphore) { if (!_closed) { try { _channelWriter.Complete(); _writerTask.GetAwaiter().GetResult(); } catch (Exception) { } try { _socket.Close(); } catch (Exception) { // ignore, we are closing anyway } finally { _closed = true; } } } }
//------------------------------------------------------------------------------ // // Method: Disconnect // //------------------------------------------------------------------------------ /// <summary> /// Disconnects a connected client and stops listening on the configured TCP port. /// </summary> public void Disconnect() { CheckNotDisposed(); try { client.Close(); DisposeClient(); listener.Stop(); connected = false; } catch (Exception e) { throw new Exception("Failed to disconnect listener.", e); } loggingUtilities.Log(this, LogLevel.Information, "Disconnected."); }
protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _client.Close(); _client.Dispose(); _disposed = true; } base.Dispose(disposing); }
/// <summary> /// Close the connection to the Folding@Home client server. /// </summary> public void Close() { // close the network stream _lockedStream.Release(); // close the connection _tcpClient.Close(); // send connected event OnConnectedChanged(new ConnectedChangedEventArgs(false)); // send status message OnStatusMessage(new StatusMessageEventArgs("Connection closed.")); }
public void Disconnect() { Console.WriteLine("Player disconnected"); _status = 0; Task.WaitAll(); if (_tcpClient.Client.Connected) { _tcpClient.Client.Disconnect(false); } _tcpClient.Close(); }
public void Disconnect() { _status = false; _receivingThread?.Wait(); _sendingThread?.Wait(); _receivingThread = null; _sendingThread = null; if (_client.Client.Connected) { _client.Client.Disconnect(false); } _client.Close(); }
public void Close() { if (_client == null) { throw new InvalidOperationException(); } #if WINRT || PCL _networkStream.Dispose(); #else _networkStream.Close(); #endif _networkStream = null; _client.Close(); _client = null; }
private bool Connect(ITcpClient client) { if (client.Connected) { return(true); } // do the connect if (Proxy == null) { //EB.Debug.Log("Connecting to " + _uri.Host + " on port " + _uri.Port); if (!client.Connect(_uri.Host, _uri.Port, 5 * 1000)) { client.Close(); Error("Connect failed", client.Error); return(false); } } else { //EB.Debug.Log("Connecting to proxy" + Proxy.Host + " on port " + Proxy.Port); if (!client.Connect(Proxy.Host, Proxy.Port, 5 * 1000)) { client.Close(); Error("Connect proxy failed", client.Error); return(false); } } // nothing should ever take longer than x seconds client.ReadTimeout = kReadTimeout * 1000; client.WriteTimeout = kWriteTimeout * 1000; _connectionFailures = 0; return(true); }
protected virtual void Dispose(bool disposing) { void DisposeOfManagedObjects() { _tcpClient?.Close(); } if (!_disposed) { if (disposing) { DisposeOfManagedObjects(); } _disposed = true; } }
internal static void CloseSocket(this ITcpClient tcpClient) { if (tcpClient == null) { return; } try { tcpClient.Close(); } catch { // ignored } }
/// <summary> /// Close the connection to the Folding@Home client server. /// </summary> public void Close() { bool connected = Connected; // close the network stream _lockedStream.Release(); // close the connection _tcpClient.Close(); if (connected != Connected) { // send connected event OnConnectedChanged(new ConnectedChangedEventArgs(false)); // maybe use Connected property? // send status message OnStatusMessage(new StatusMessageEventArgs("Connection closed.", TraceLevel.Info)); } }
void DoConnectSafe(object state) { try { Thread.CurrentThread.Name = "websocket"; } catch { } try { if (DoConnect()) { if (SendUpgradeRequest()) { MainLoop(); } } } catch (System.Threading.ThreadAbortException) { // don't care } catch (System.Exception e) { Error("exception " + e.ToString()); } _state = WebSocketState.None; EB.Debug.Log("Disconnecting from socket " + _uri); try { if (_client != null) { _client.Close(); } } catch { } _client = null; if (_parent != null) { _parent.DidClose(this); } }
/// <summary> /// /// </summary> /// <param name="requests">Requests to send</param> /// <returns>Responses from the server</returns> public Message[] SendRequests(Message[] requests) { byte[] requestsBytes; int count = _converter.MessagesToBytes(out requestsBytes, requests); ITcpClient _tcpClient = _tcpFactory.Create(); _tcpClient.Connect(_address, _port); using (INetworkStream networkStream = _tcpClient.GetStream()) { networkStream.Write(requestsBytes, count); byte[] responseBytes = new byte[Properties.Settings.Default.MaxBufferSize]; int len = networkStream.Read(responseBytes, Properties.Settings.Default.MaxBufferSize); networkStream.Close(); _tcpClient.Close(); return(_converter.BytesToMessages(responseBytes, len)); } }
/// <summary> /// Close the connection to the Folding@Home client server. /// </summary> public void Close() { // stop the timer _timer.Stop(); // close the network stream if (_stream != null) { _stream.Close(); } // remove reference to the network stream _stream = null; // close the actual connection _tcpClient.Close(); // send connected event OnConnectedChanged(new ConnectedChangedEventArgs(false)); // maybe use Connected property? // send status message OnStatusMessage(new StatusMessageEventArgs("Connection closed.", TraceLevel.Info)); }
public async Task Open(CancellationToken ct) { if (_client != null) { throw new InvalidOperationException(); } _client = _tcpClientFactory.Create(_address, false); var isConnected = false; try { _client.ReadWriteTimeout = ReadWriteTimeout; _client.Timeout = Timeout; // Connect await _client.Open(ct); isConnected = true; // Authenticate with proxy server await Authenticate(ct); // Open connection to destination address through proxy server await Connect(_destinationAddress, ct); // Do we need SSL? _networkStream = _client.GetStream(); if (_useSsl) { _networkStream = await _tcpClientFactory.CreateSslStream(_networkStream, _destinationAddress.Host); } } catch { if (isConnected) { _client.Close(); } _client = null; throw; } }
public void Close() { lock (_semaphore) { if (!_closed) { try { m_socket.Close(); } catch { // ignore, we are closing anyway } finally { _closed = true; } } } }
public void Close() { lock (_semaphore) { if (!_closed) { try { m_socket.Close(); } //catch (Exception) //{ // // ignore, we are closing anyway //} finally { _closed = true; } } } }
/// <summary> /// Notifies sessions of closing and then closes the network stream and client (does not raise events) /// </summary> private void _closeInternal() { // close and clear any pending sessions foreach (var s in _pendingSessions) { s.Value.NotifyConnectionClose(); } _pendingSessions.Clear(); // close and clear any active sessions foreach (var s in _activeSessions) { s.Value.NotifyConnectionClose(); } _activeSessions.Clear(); // TODO: use in network stream read _cts.Cancel(); try { _streamDecoderTask.Dispose(); } catch { } // close transport resources try { _networkStream.Close(); } catch { } try { _tcpClient.Close(); } catch { } }
/// <summary> /// Connect to a Folding@Home client server. /// </summary> /// <param name="host">Hostname or IP address.</param> /// <param name="port">TCP port number.</param> /// <param name="password">Server password.</param> /// <exception cref="InvalidOperationException">Connection is already connected.</exception> /// <exception cref="ArgumentNullException"><paramref name="host"/> or <paramref name="password"/> is null.</exception> /// <exception cref="TimeoutException">Connection attempt timed out.</exception> public void Connect(string host, int port, string password) { // check connection status, callers should make sure no connection exists first if (Connected) { throw new InvalidOperationException("Client is already connected."); } if (host == null) { throw new ArgumentNullException("host"); } if (password == null) { throw new ArgumentNullException("password"); } if (_tcpClient != null) { _tcpClient.Dispose(); } _tcpClient = CreateClient(); IAsyncResult ar = _tcpClient.BeginConnect(host, port, null, null); try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(ConnectTimeout), false)) { _tcpClient.Close(); throw new TimeoutException("Client connection has timed out."); } _tcpClient.EndConnect(ar); _stream = _tcpClient.GetStream(); if (password.Length != 0) { // send authentication SendCommand("auth " + password); } if (Connected) { // send connected event OnConnectedChanged(new ConnectedChangedEventArgs(true)); // maybe use Connected property? // send status message OnStatusMessage(new StatusMessageEventArgs(String.Format(CultureInfo.CurrentCulture, "Connected to {0}:{1}", host, port), TraceLevel.Info)); // start listening for messages // from the network stream _timer.Start(); } } finally { /* * when running on Mono, if we time out connecting, * TcpClient.Close() (above) causes asynchronous access * (coming from BeginConnect-related path) to AsyncWaitHandle. * This opens a race window with closing the handle below. * * Unfortunate chain of events results in the following: * * Unhandled Exception: System.ObjectDisposedException: The object was used after being disposed. * at System.Threading.WaitHandle.CheckDisposed () * at System.Threading.EventWaitHandle.Set () * at (wrapper remoting-invoke-with-check) System.Threading.EventWaitHandle:Set () * at System.Net.Sockets.Socket+SocketAsyncResult.set_IsCompleted (Boolean value) * at System.Net.Sockets.Socket+SocketAsyncResult.Complete () * at System.Net.Sockets.Socket+SocketAsyncResult.Complete (System.Exception e) * at System.Net.Sockets.Socket+Worker.Connect () * at System.Net.Sockets.Socket+Worker.DispatcherCB (System.Net.Sockets.SocketAsyncResult sar) * * As Mono's TcpClient.Close() signals AsyncWaitHandle, we can * just wait on it before proceeding. * * Note: we can't wait on the handle right after closing TcpClient * because closing the client may throw. * */ if (IsRunningOnMono) { ar.AsyncWaitHandle.WaitOne(); } ar.AsyncWaitHandle.Close(); } }
/// <summary> /// Connect to a Folding@Home client server. /// </summary> /// <param name="host">Hostname or IP address.</param> /// <param name="port">TCP port number.</param> /// <param name="password">Server password.</param> /// <exception cref="InvalidOperationException">Connection is already connected.</exception> /// <exception cref="ArgumentNullException"><paramref name="host"/> or <paramref name="password"/> is null.</exception> /// <exception cref="TimeoutException">Connection attempt timed out.</exception> public void Connect(string host, int port, string password) { // check connection status, callers should make sure no connection exists first if (Connected) throw new InvalidOperationException("Client is already connected."); if (host == null) throw new ArgumentNullException("host"); if (password == null) throw new ArgumentNullException("password"); if (_tcpClient != null) { _tcpClient.Dispose(); } _tcpClient = CreateClient(); IAsyncResult ar = _tcpClient.BeginConnect(host, port, null, null); try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(ConnectTimeout), false)) { _tcpClient.Close(); throw new TimeoutException("Client connection has timed out."); } _tcpClient.EndConnect(ar); _stream = _tcpClient.GetStream(); if (password.Length != 0) { // send authentication SendCommand("auth " + password); } if (Connected) { // send connected event OnConnectedChanged(new ConnectedChangedEventArgs(true)); // maybe use Connected property? // send status message OnStatusMessage(new StatusMessageEventArgs(String.Format(CultureInfo.CurrentCulture, "Connected to {0}:{1}", host, port), TraceLevel.Info)); // start listening for messages // from the network stream _timer.Start(); } } finally { ar.AsyncWaitHandle.Close(); } }
/// <summary> /// Starts listening to the WAS. Uses the event 'WasConnectionStateChanged' to report changes of the connection-state. /// If any data is on the client-stream available, the method will report the progress using the 'WasObjectChanged' event. /// This method also starts a new timer to send the KeepAlive-Message. /// </summary> private void StartWorker(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; ITcpClient tcpClient = null; System.Timers.Timer t = null; try { tcpClient = this.mCoreObjectFactory.CreateTcpClient(); tcpClient.Connect(AicSettings.Global.WasIp, AicSettings.Global.WasPort); t = new System.Timers.Timer(Constants.WasKeepAliveTimeout.TotalMilliseconds); t.Elapsed += delegate { SendKeepAliveMessage(tcpClient); }; t.Start(); tcpClient.GetStream().Write(Constants.GetAlarmsCommandBytes, 0, Constants.GetAlarmsCommandBytes.Length); if (this.WasConnectionStateChanged != null) { Thread eventThread = new Thread(new ThreadStart(delegate { this.WasConnectionStateChanged(true, false); })) { IsBackground = true }; eventThread.Start(); } while (!worker.CancellationPending) { // Check if the connection to the WAS got lost if (!tcpClient.IsConnected()) { this.mLogger.LogError("WAS disconnected while waiting for new data", ErrorType.WasListener_WasDisconnectWhileWaiting); throw new SocketException(); } // Check if any data from the WAS is available else if (!tcpClient.GetStream().DataAvailable) { Thread.Sleep((int)Constants.WasRequestCycleTimeout.TotalMilliseconds); continue; } this.HandleWasData(tcpClient); } } catch (Exception ex) { this.mLogger.LogError("(WasListener/StartWorker/Exception)", ErrorType.Undefined, ex); throw ex; } finally { lock (this.mLocker) { if (t != null) { t.Dispose(); } if (tcpClient != null) { if (tcpClient.Connected) { // The networkstream will not close itself - see MSDN IStream networkStream = tcpClient.GetStream(); networkStream.Close(); } tcpClient.Close(); } this.mIsRunning = false; } } }
/// <summary> /// Connect to a Folding@Home client server. /// </summary> /// <param name="host">Hostname or IP address.</param> /// <param name="port">TCP port number.</param> /// <param name="password">Server password.</param> /// <exception cref="InvalidOperationException">Connection is already connected.</exception> /// <exception cref="ArgumentNullException"><paramref name="host"/> or <paramref name="password"/> is null.</exception> /// <exception cref="TimeoutException">Connection attempt timed out.</exception> public void Connect(string host, int port, string password) { // check connection status, callers should make sure no connection exists first if (Connected) throw new InvalidOperationException("Client is already connected."); if (host == null) throw new ArgumentNullException("host"); if (password == null) throw new ArgumentNullException("password"); if (_tcpClient != null) { _tcpClient.Dispose(); } _tcpClient = CreateClient(); IAsyncResult ar = _tcpClient.BeginConnect(host, port, null, null); try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(ConnectTimeout), false)) { _tcpClient.Close(); throw new TimeoutException("Client connection has timed out."); } _tcpClient.EndConnect(ar); _stream = _tcpClient.GetStream(); if (password.Length != 0) { // send authentication SendCommand("auth " + password); } if (Connected) { // send connected event OnConnectedChanged(new ConnectedChangedEventArgs(true)); // maybe use Connected property? // send status message OnStatusMessage(new StatusMessageEventArgs(String.Format(CultureInfo.CurrentCulture, "Connected to {0}:{1}", host, port), TraceLevel.Info)); // start listening for messages // from the network stream _timer.Start(); } } finally { /* * when running on Mono, if we time out connecting, * TcpClient.Close() (above) causes asynchronous access * (coming from BeginConnect-related path) to AsyncWaitHandle. * This opens a race window with closing the handle below. * * Unfortunate chain of events results in the following: Unhandled Exception: System.ObjectDisposedException: The object was used after being disposed. at System.Threading.WaitHandle.CheckDisposed () at System.Threading.EventWaitHandle.Set () at (wrapper remoting-invoke-with-check) System.Threading.EventWaitHandle:Set () at System.Net.Sockets.Socket+SocketAsyncResult.set_IsCompleted (Boolean value) at System.Net.Sockets.Socket+SocketAsyncResult.Complete () at System.Net.Sockets.Socket+SocketAsyncResult.Complete (System.Exception e) at System.Net.Sockets.Socket+Worker.Connect () at System.Net.Sockets.Socket+Worker.DispatcherCB (System.Net.Sockets.SocketAsyncResult sar) * As Mono's TcpClient.Close() signals AsyncWaitHandle, we can * just wait on it before proceeding. * * Note: we can't wait on the handle right after closing TcpClient * because closing the client may throw. * */ if (IsRunningOnMono) { ar.AsyncWaitHandle.WaitOne(); } ar.AsyncWaitHandle.Close(); } }
private ITcpClient GetClient() { lock (connections) { List <ITcpClient> clients = null; if (connections.TryGetValue(connectionKey, out clients)) { // remove bad clients //Debug.Log("removing clients " + connectionKey); clients.RemoveAll(delegate(ITcpClient client) { if (!client.Connected || Time.Since(client.LastTime) >= kConnectionTimeout) { //Debug.Log("removing client"); client.Close(); return(true); } return(false); }); if (clients.Count > 0) { var client = clients[clients.Count - 1]; clients.RemoveAt(clients.Count - 1); //Debug.Log("reusing client " + Time.Since(client.LastTime)); return(client); } } } //Debug.Log("creating new client " + connectionKey); ITcpClient tcpClient = TcpClientFactory.Create(_uri.Scheme == "https"); if (Proxy != null && _uri.Scheme == "https") { (tcpClient as TcpClientEvent).ConnectedEvent += delegate(object sender) { const string CRLF = "\r\n"; string request = "CONNECT " + _uri.Host + ":" + _uri.Port + " HTTP/1.1" + CRLF + "Host: " + _uri.HostAndPort + CRLF + CRLF; var bytes = Encoding.GetBytes(request); tcpClient.Write(bytes, 0, bytes.Length); string header = ReadLine(tcpClient).ToLower(); if (!header.StartsWith("http/1.1 200 connection established") && !header.StartsWith("http/1.0 200 connection established")) { tcpClient.Close(); tcpClient = null; throw new System.Net.WebException("failed to connect to proxy"); } // read the headers while (true) { var line = ReadLine(tcpClient); //Debug.Log("line: " + line + " " + line.Length); if (line.Length == 0) { break; } } }; } return(tcpClient); }