public bool DisConnect() { if (IsConnect) { _socket?.Close(); } _socketArg?.Dispose(); _socket?.Dispose(); _socket = null; _socketArg = null; _isConnect = false; _subSocketArgFlag = false; DisconnectEvent?.Invoke(this); return(true); }
public void Dispose() { if (_disposed.TrySetValue(0, 1)) { _socketAsyncEventArgs?.Dispose(); } }
public override void Disconnect() { _isConnected = false; _socket?.Dispose(); receiveEvent?.Dispose(); OnDisconnect(); }
public void Stop() { SessionMgr.Stop(); _listener.Close(); _acceptEvent?.Dispose(); Logger.Ins.Debug("Server stopped!"); }
/// <summary> /// 停止接收数据 /// </summary> public void StopReceive() { using (new LockWait(ref _lParam)) { _isStoped = true; Socket.Dispose(); _recArgs?.Dispose(); } }
public void Close() { acceptSocket?.Dispose(); acceptSocket = null; Socket s = socket; socket = null; s?.Dispose(); args?.Dispose(); }
private void DisposeStream() { _receiveEventArgs?.Dispose(); _receiveEventArgs = null; _stream?.Close(); _stream?.Dispose(); _stream = null; _tcpClient?.Close(); _tcpClient?.Dispose(); _tcpClient = null; }
public void Close() { pumpEnabled = false; acceptSocket?.Dispose(); acceptSocket = null; Socket s = socket; socket = null; s?.Dispose(); args?.Dispose(); }
public override void Stop() { _isRunning = false; _resetEvent?.Dispose(); _resetEvent = null; _accepSocketEvent?.Dispose(); _accepSocketEvent = null; _loopTask?.Wait(); _loopTask = null; }
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { if (_disposed) { return; } _disposed = true; _clientSocket?.Dispose(); _socketMessageHandler.Dispose(); _readEventArgs?.Dispose(); MessageReceived = null; Connected = null; }
public void Dispose() { if (_socket != null) { if (_socket.Connected) { _socket.Shutdown(SocketShutdown.Both); _socket.Close(); } _socket.Dispose(); } _socketAsyncEventArgs?.Dispose(); }
/// <summary> /// 结束本地代理会话 /// </summary> public void Close() { IsRuning = false; if (Socket == null) { return; } if (Interlocked.CompareExchange(ref Closing, 1, 0) == 0) { //desTcpCliet?.Close(); //cTcpClient.Close(); try { Socket.Shutdown(SocketShutdown.Both); } catch { } try { Socket.Close(); } catch { } Msaea?.Dispose(); } }
private void CreateSocketAsyncEvent(EndPoint iPEndPoint) { _sendEventArgs?.Dispose(); _recvEventArgs?.Dispose(); _sendEventArgs = new SocketAsyncEventArgs { RemoteEndPoint = iPEndPoint }; _sendEventArgs.Completed += IoCompleted; _recvEventArgs = new SocketAsyncEventArgs { RemoteEndPoint = iPEndPoint }; _recvEventArgs.SetBuffer(new byte[MaxPackSize], 0, MaxPackSize); _recvEventArgs.Completed += IoCompleted; }
/// <summary> /// 结束本地代理会话 /// </summary> public void Close(ClientErrorType clientErrorType) { if (Interlocked.CompareExchange(ref Closing, 1, 0) == 0) { desTcpCliet?.Close(); cTcpClient.Close(); Rsaea?.Dispose(); DRsaea?.Dispose(); Ssaea?.Dispose(); DSsaea?.Dispose(); OnClose?.Invoke(HttpProxySessionInfo, clientErrorType); } }
void Cleanup () { if (send != null) { send.Completed -= AsyncOperationCompleted; send.AcceptSocket = null; send?.Dispose (); send = null; } if (recv != null) { recv.Completed -= AsyncOperationCompleted; recv.AcceptSocket = null; recv.Dispose (); recv = null; } }
/// <summary> /// Handles a read complete event. /// </summary> private void OnReadComplete(object sender, SocketAsyncEventArgs e) { lock (m_readLock) { ServiceResult error = null; try { bool innerCall = m_readState == ReadState.ReadComplete; error = DoReadComplete(e); // to avoid recursion, inner calls of OnReadComplete return // after processing the ReadComplete and let the outer call handle it if (!innerCall && !ServiceResult.IsBad(error)) { while (ReadNext()) { ; } } } catch (Exception ex) { Utils.Trace(ex, "Unexpected error during OnReadComplete,"); error = ServiceResult.Create(ex, StatusCodes.BadTcpInternalError, ex.Message); } finally { e?.Dispose(); } if (ServiceResult.IsBad(error)) { if (m_receiveBuffer != null) { m_bufferManager.ReturnBuffer(m_receiveBuffer, "OnReadComplete"); m_receiveBuffer = null; } m_sink?.OnReceiveError(this, error); } } }
protected override void Dispose(bool disposing) { if (disposing) { if (ownsSocket && connected) { ownsSocket = false; Disconnect(); } else { send?.Dispose(); send = null; recv?.Dispose(); recv = null; } } base.Dispose(disposing); }
private void Dispose(bool disposing) { if (Interlocked.Exchange(ref _isDisposed, 1) == 0) { if (disposing) { _socket?.Close(); _connectArgs?.Dispose(); } if (_doBind == 1 && _isBound == 0) { OnBindingFailed(); } else if (_doConnect == 1 && _connected == 0) { OnConnectionFailed(); } OnDisposed(); } }
private void Dispose(bool disposing) { if (Interlocked.Exchange(ref _isDisposed, 1) == 0) { if (disposing) { _socket?.Close(); _acceptArgs?.Dispose(); } if (_doBind == 1 && _isBound == 0) { OnBindingFailed(); } else if (_doListen == 1 && _listening == 0) { OnListeningFailed(); } OnDisposed(); } }
public static int ReadPartial(Socket socket, byte[] buffer, int offset, int size, TimeSpan timeout) { #if FEATURE_SOCKET_SYNC socket.ReceiveTimeout = (int)timeout.TotalMilliseconds; try { return(socket.Receive(buffer, offset, size, SocketFlags.None)); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.TimedOut) { throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, "Socket read operation has timed out after {0:F0} milliseconds.", timeout.TotalMilliseconds)); } throw; } #elif FEATURE_SOCKET_EAP var receiveCompleted = new ManualResetEvent(false); var sendReceiveToken = new PartialSendReceiveToken(socket, receiveCompleted); var args = new SocketAsyncEventArgs { RemoteEndPoint = socket.RemoteEndPoint, UserToken = sendReceiveToken }; args.Completed += ReceiveCompleted; args.SetBuffer(buffer, offset, size); try { if (socket.ReceiveAsync(args)) { if (!receiveCompleted.WaitOne(timeout)) { throw new SshOperationTimeoutException( string.Format( CultureInfo.InvariantCulture, "Socket read operation has timed out after {0:F0} milliseconds.", timeout.TotalMilliseconds)); } } if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } return(args.BytesTransferred); } finally { // initialize token to avoid the waithandle getting used after it's disposed args.UserToken = null; args.Dispose(); receiveCompleted.Dispose(); } #else #error Receiving data from a Socket is not implemented. #endif }
protected void ProcessConnect(Socket socket, object state, SocketAsyncEventArgs e, Exception exception) { if (exception != null) { m_InConnecting = false; OnError(exception); if (e != null) { e.Dispose(); } return; } if (e != null && e.SocketError != SocketError.Success) { m_InConnecting = false; OnError(new SocketException((int)e.SocketError)); e.Dispose(); return; } if (socket == null) { m_InConnecting = false; OnError(new SocketException((int)SocketError.ConnectionAborted)); return; } //To walk around a MonoTouch's issue //one user reported in some cases the e.SocketError = SocketError.Succes but the socket is not connected in MonoTouch if (!socket.Connected) { m_InConnecting = false; var socketError = SocketError.HostUnreachable; try { socketError = (SocketError)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error); } catch (Exception) { socketError = SocketError.HostUnreachable; } OnError(new SocketException((int)socketError)); return; } if (e == null) { e = new SocketAsyncEventArgs(); } e.Completed += SocketEventArgsCompleted; Client = socket; m_InConnecting = false; try { // mono may throw an exception here LocalEndPoint = socket.LocalEndPoint; } catch { } var finalRemoteEndPoint = e.RemoteEndPoint != null ? e.RemoteEndPoint : socket.RemoteEndPoint; if (string.IsNullOrEmpty(HostName)) { HostName = GetHostOfEndPoint(finalRemoteEndPoint); } else// connect with DnsEndPoint { var finalDnsEndPoint = finalRemoteEndPoint as DnsEndPoint; if (finalDnsEndPoint != null) { var hostName = finalDnsEndPoint.Host; if (!string.IsNullOrEmpty(hostName) && !HostName.Equals(hostName, StringComparison.OrdinalIgnoreCase)) { HostName = hostName; } } } try { //Set keep alive Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); } catch { } OnGetSocket(e); }
/// <summary> /// Disconnect the client (synchronous) /// </summary> /// <returns>'true' if the client was successfully disconnected, 'false' if the client is already disconnected</returns> public virtual bool Disconnect() { if (!IsConnected && !IsConnecting) { return(false); } // Cancel connecting operation if (IsConnecting) { Socket.CancelConnectAsync(_connectEventArg); } // Reset event args _connectEventArg.Completed -= OnAsyncCompleted; _receiveEventArg.Completed -= OnAsyncCompleted; _sendEventArg.Completed -= OnAsyncCompleted; // Call the client disconnecting handler OnDisconnecting(); try { try { // Shutdown the socket associated with the client Socket.Shutdown(SocketShutdown.Both); } catch (SocketException) {} // Close the client socket Socket.Close(); // Dispose the client socket Socket.Dispose(); // Dispose event arguments _connectEventArg.Dispose(); _receiveEventArg.Dispose(); _sendEventArg.Dispose(); // Update the client socket disposed flag IsSocketDisposed = true; } catch (ObjectDisposedException) {} // Update the connected flag IsConnected = false; // Update sending/receiving flags _receiving = false; _sending = false; // Clear send/receive buffers ClearBuffers(); // Call the client disconnected handler OnDisconnected(); return(true); }
/// <summary> /// Reads the next block of data from the socket. /// </summary> private void ReadNextBlock() { Socket socket = null; // check if already closed. lock (m_socketLock) { if (m_socket == null) { if (m_receiveBuffer != null) { m_bufferManager.ReturnBuffer(m_receiveBuffer, "ReadNextBlock"); m_receiveBuffer = null; } m_readState = ReadState.NotConnected; return; } socket = m_socket; // avoid stale ServiceException when socket is disconnected if (!socket.Connected) { m_readState = ReadState.NotConnected; return; } } BufferManager.LockBuffer(m_receiveBuffer); var args = new SocketAsyncEventArgs(); try { m_readState = ReadState.Receive; args.SetBuffer(m_receiveBuffer, m_bytesReceived, m_bytesToReceive - m_bytesReceived); args.Completed += m_readComplete; if (!socket.ReceiveAsync(args)) { // I/O completed synchronously if (args.SocketError != SocketError.Success) { throw ServiceResultException.Create(StatusCodes.BadTcpInternalError, args.SocketError.ToString()); } // set state to inner complete m_readState = ReadState.ReadComplete; m_readComplete(null, args); } } catch (ServiceResultException) { args?.Dispose(); BufferManager.UnlockBuffer(m_receiveBuffer); throw; } catch (Exception ex) { args?.Dispose(); BufferManager.UnlockBuffer(m_receiveBuffer); throw ServiceResultException.Create(StatusCodes.BadTcpInternalError, ex, "BeginReceive failed."); } }
/// <summary> /// Connect the client (synchronous) /// </summary> /// <remarks> /// Please note that synchronous connect will not receive data automatically! /// You should use Receive() or ReceiveAsync() method manually after successful connection. /// </remarks> /// <returns>'true' if the client was successfully connected, 'false' if the client failed to connect</returns> public virtual bool Connect() { if (IsConnected || IsConnecting) { return(false); } // Setup buffers _receiveBuffer = new Buffer(); _sendBufferMain = new Buffer(); _sendBufferFlush = new Buffer(); // Setup event args _connectEventArg = new SocketAsyncEventArgs(); _connectEventArg.RemoteEndPoint = Endpoint; _connectEventArg.Completed += OnAsyncCompleted; _receiveEventArg = new SocketAsyncEventArgs(); _receiveEventArg.Completed += OnAsyncCompleted; _sendEventArg = new SocketAsyncEventArgs(); _sendEventArg.Completed += OnAsyncCompleted; // Create a new client socket Socket = CreateSocket(); // Update the client socket disposed flag IsSocketDisposed = false; // Apply the option: dual mode (this option must be applied before connecting) if (Socket.AddressFamily == AddressFamily.InterNetworkV6) { Socket.DualMode = OptionDualMode; } // Call the client connecting handler OnConnecting(); try { // Connect to the server Socket.Connect(Endpoint); } catch (SocketException ex) { // Call the client error handler SendError(ex.SocketErrorCode); // Reset event args _connectEventArg.Completed -= OnAsyncCompleted; _receiveEventArg.Completed -= OnAsyncCompleted; _sendEventArg.Completed -= OnAsyncCompleted; // Call the client disconnecting handler OnDisconnecting(); // Close the client socket Socket.Close(); // Dispose the client socket Socket.Dispose(); // Dispose event arguments _connectEventArg.Dispose(); _receiveEventArg.Dispose(); _sendEventArg.Dispose(); // Call the client disconnected handler OnDisconnected(); return(false); } // Apply the option: keep alive if (OptionKeepAlive) { Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); } // Apply the option: no delay if (OptionNoDelay) { Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); } // Prepare receive & send buffers _receiveBuffer.Reserve(OptionReceiveBufferSize); _sendBufferMain.Reserve(OptionSendBufferSize); _sendBufferFlush.Reserve(OptionSendBufferSize); // Reset statistic BytesPending = 0; BytesSending = 0; BytesSent = 0; BytesReceived = 0; // Update the connected flag IsConnected = true; // Call the client connected handler OnConnected(); // Call the empty send buffer handler if (_sendBufferMain.IsEmpty) { OnEmpty(); } return(true); }
private void DisposeSocketIfNotNull() { _acceptSocket?.Dispose(); _socketArgs?.Dispose(); }
public void Dispose() { _eventArgs.Dispose(); }
public static Socket Connect(IPEndPoint remoteEndpoint, TimeSpan connectTimeout) { var socket = new Socket(remoteEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; #if FEATURE_SOCKET_EAP var connectCompleted = new ManualResetEvent(false); var args = new SocketAsyncEventArgs { UserToken = connectCompleted, RemoteEndPoint = remoteEndpoint }; args.Completed += ConnectCompleted; if (socket.ConnectAsync(args)) { if (!connectCompleted.WaitOne(connectTimeout)) { // avoid ObjectDisposedException in ConnectCompleted args.Completed -= ConnectCompleted; // dispose Socket socket.Dispose(); // dispose ManualResetEvent connectCompleted.Dispose(); // dispose SocketAsyncEventArgs args.Dispose(); throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds)); } } // dispose ManualResetEvent connectCompleted.Dispose(); if (args.SocketError != SocketError.Success) { var socketError = (int)args.SocketError; // dispose Socket socket.Dispose(); // dispose SocketAsyncEventArgs args.Dispose(); throw new SocketException(socketError); } // dispose SocketAsyncEventArgs args.Dispose(); return(socket); #elif FEATURE_SOCKET_APM var connectResult = socket.BeginConnect(remoteEndpoint, null, null); if (!connectResult.AsyncWaitHandle.WaitOne(connectTimeout, false)) { throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds)); } socket.EndConnect(connectResult); return(socket); #elif FEATURE_SOCKET_TAP if (!socket.ConnectAsync(remoteEndpoint).Wait(connectTimeout)) { throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds)); } return(socket); #else #error Connecting to a remote endpoint is not implemented. #endif }
private void SocketOperationCompleted(object sender, SocketAsyncEventArgs e) { var asyncContinuation = e.UserToken as AsyncContinuation; Exception error = null; if (e.SocketError != SocketError.Success) { error = new IOException("Error: " + e.SocketError); } e.Dispose(); if (asyncContinuation != null) { asyncContinuation(error); } }
/// <summary> /// Dispose protocol, automatically called by client.Dispose and server.Dispose /// </summary> public virtual void Dispose() { AcceptArgs?.Dispose(); ReceiveBuffer?.Dispose(); NetworkStream?.Dispose(); }
/// <summary> /// Receives data from a bound <see cref="Socket"/>into a receive buffer. /// </summary> /// <param name="socket"></param> /// <param name="buffer">An array of type <see cref="byte"/> that is the storage location for the received data. </param> /// <param name="offset">The position in <paramref name="buffer"/> parameter to store the received data.</param> /// <param name="size">The number of bytes to receive.</param> /// <param name="timeout">Specifies the amount of time after which the call will time out.</param> /// <returns> /// The number of bytes received. /// </returns> /// <remarks> /// If no data is available for reading, the <see cref="Read(Socket,byte[], int, int, TimeSpan)"/> method will /// block until data is available or the time-out value was exceeded. If the time-out value was exceeded, the /// <see cref="Read(Socket,byte[], int, int, TimeSpan)"/> call will throw a <see cref="SshOperationTimeoutException"/>. /// If you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the /// <see cref="Read(Socket,byte[], int, int, TimeSpan)"/> method will complete immediately and throw a <see cref="SocketException"/>. /// </remarks> public static int Read(Socket socket, byte[] buffer, int offset, int size, TimeSpan timeout) { #if FEATURE_SOCKET_SYNC var totalBytesRead = 0; var totalBytesToRead = size; socket.ReceiveTimeout = (int)timeout.TotalMilliseconds; do { try { var bytesRead = socket.Receive(buffer, offset + totalBytesRead, totalBytesToRead - totalBytesRead, SocketFlags.None); if (bytesRead == 0) { return(0); } totalBytesRead += bytesRead; } catch (SocketException ex) { if (IsErrorResumable(ex.SocketErrorCode)) { ThreadAbstraction.Sleep(30); continue; } if (ex.SocketErrorCode == SocketError.TimedOut) { throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, "Socket read operation has timed out after {0:F0} milliseconds.", timeout.TotalMilliseconds)); } throw; } }while (totalBytesRead < totalBytesToRead); return(totalBytesRead); #elif FEATURE_SOCKET_EAP var receiveCompleted = new ManualResetEvent(false); var sendReceiveToken = new BlockingSendReceiveToken(socket, buffer, offset, size, receiveCompleted); var args = new SocketAsyncEventArgs { UserToken = sendReceiveToken, RemoteEndPoint = socket.RemoteEndPoint }; args.Completed += ReceiveCompleted; args.SetBuffer(buffer, offset, size); try { if (socket.ReceiveAsync(args)) { if (!receiveCompleted.WaitOne(timeout)) { throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, "Socket read operation has timed out after {0:F0} milliseconds.", timeout.TotalMilliseconds)); } } if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } return(sendReceiveToken.TotalBytesTransferred); } finally { // initialize token to avoid the waithandle getting used after it's disposed args.UserToken = null; args.Dispose(); receiveCompleted.Dispose(); } #else #error Receiving data from a Socket is not implemented. #endif }
private void SocketOperationCompleted(object sender, SocketAsyncEventArgs e) { lock (this) { this.asyncOperationInProgress = false; var asyncContinuation = e.UserToken as AsyncContinuation; if (e.SocketError != SocketError.Success) { this.pendingError = new IOException("Error: " + e.SocketError); } e.Dispose(); if (asyncContinuation != null) { asyncContinuation(this.pendingError); } } this.ProcessNextQueuedItem(); }
public static void Send(Socket socket, byte[] data, int offset, int size) { #if FEATURE_SOCKET_SYNC var totalBytesSent = 0; // how many bytes are already sent var totalBytesToSend = size; do { try { var bytesSent = socket.Send(data, offset + totalBytesSent, totalBytesToSend - totalBytesSent, SocketFlags.None); if (bytesSent == 0) { throw new SshConnectionException("An established connection was aborted by the server.", DisconnectReason.ConnectionLost); } totalBytesSent += bytesSent; } catch (SocketException ex) { if (IsErrorResumable(ex.SocketErrorCode)) { // socket buffer is probably full, wait and try again ThreadAbstraction.Sleep(30); } else { throw; // any serious error occurr } } } while (totalBytesSent < totalBytesToSend); #elif FEATURE_SOCKET_EAP var sendCompleted = new ManualResetEvent(false); var sendReceiveToken = new BlockingSendReceiveToken(socket, data, offset, size, sendCompleted); var socketAsyncSendArgs = new SocketAsyncEventArgs { RemoteEndPoint = socket.RemoteEndPoint, UserToken = sendReceiveToken }; socketAsyncSendArgs.SetBuffer(data, offset, size); socketAsyncSendArgs.Completed += SendCompleted; try { if (socket.SendAsync(socketAsyncSendArgs)) { if (!sendCompleted.WaitOne()) { throw new SocketException((int)SocketError.TimedOut); } } if (socketAsyncSendArgs.SocketError != SocketError.Success) { throw new SocketException((int)socketAsyncSendArgs.SocketError); } if (sendReceiveToken.TotalBytesTransferred == 0) { throw new SshConnectionException("An established connection was aborted by the server.", DisconnectReason.ConnectionLost); } } finally { // initialize token to avoid the completion waithandle getting used after it's disposed socketAsyncSendArgs.UserToken = null; socketAsyncSendArgs.Dispose(); sendCompleted.Dispose(); } #else #error Sending data to a Socket is not implemented. #endif }