Dispose() public method

public Dispose ( ) : void
return void
示例#1
0
        /// <summary>
        /// Dispose of the TCP client.
        /// </summary>
        /// <param name="disposing">Dispose of resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                try
                {
                    _WriteSemaphore.Wait();
                    _ReadSemaphore.Wait();

                    if (_SslStream != null)
                    {
                        _SslStream.Close();
                    }

                    if (_NetworkStream != null)
                    {
                        _NetworkStream.Close();
                    }

                    if (_TcpClient != null)
                    {
                        _TcpClient.Close();
                        _TcpClient.Dispose();
                        _TcpClient = null;
                    }
                }
                finally
                {
                    _ReadSemaphore.Release();
                    _WriteSemaphore.Release();
                }

                _IsConnected = false;
            }
        }
示例#2
0
 public void Reset()
 {
     _client?.Close();
     _client?.Dispose();
     _stream?.Dispose();
     _client = new System.Net.Sockets.TcpClient();
 }
        protected override async Task Send(SyslogMessage syslogMessage)
        {
            var client = new TcpClient();
            client.ConnectAsync(Hostname, LogglyConfig.Instance.Transport.EndpointPort).Wait();

            try
            {
                byte[] messageBytes = syslogMessage.GetBytes();
                var networkStream = await GetNetworkStream(client).ConfigureAwait(false);
                await networkStream.WriteAsync(messageBytes, 0, messageBytes.Length).ConfigureAwait(false);
                await networkStream.FlushAsync().ConfigureAwait(false);
            }
            catch (AuthenticationException e)
            {
                LogglyException.Throw(e, e.Message);
            }
            finally
            {
#if NET_STANDARD
                client.Dispose();
#else
                client.Close();
#endif
            }

        }
示例#4
0
        public void Dispose()
        {
            if (TokenSource != null)
            {
                if (!TokenSource.IsCancellationRequested)
                {
                    TokenSource.Cancel();
                    TokenSource.Dispose();
                }
            }

            if (_SslStream != null)
            {
                _SslStream.Close();
            }

            if (_NetworkStream != null)
            {
                _NetworkStream.Close();
            }

            if (_TcpClient != null)
            {
                _TcpClient.Close();
                _TcpClient.Dispose();
            }
        }
 private void SendHttpResponse(TcpClient client, Stream stream, HttpListenerResponse response, byte[] body)
 {
     // Status line
     var statusLine = $"HTTP/1.1 {response.StatusCode} {response.StatusDescription}\r\n";
     var statusBytes = Encoding.ASCII.GetBytes(statusLine);
     stream.Write(statusBytes, 0, statusBytes.Length);
     // Headers
     foreach (var key in response.Headers.AllKeys)
     {
         var value = response.Headers[key];
         var line = $"{key}: {value}\r\n";
         var lineBytes = Encoding.ASCII.GetBytes(line);
         stream.Write(lineBytes, 0, lineBytes.Length);
     }
     // Content-Type header
     var contentType = Encoding.ASCII.GetBytes($"Content-Type: {response.ContentType}\r\n");
     stream.Write(contentType, 0, contentType.Length);
     // Content-Length header
     var contentLength = Encoding.ASCII.GetBytes($"Content-Length: {body.Length}\r\n");
     stream.Write(contentLength, 0, contentLength.Length);
     // "Connection: close", to tell the client we can't handle persistent TCP connections
     var connection = Encoding.ASCII.GetBytes("Connection: close\r\n");
     stream.Write(connection, 0, connection.Length);
     // Blank line to indicate end of headers
     stream.Write(new[] { (byte)'\r', (byte)'\n' }, 0, 2);
     // Body
     stream.Write(body, 0, body.Length);
     stream.Flush();
     // Graceful socket shutdown
     client.Client.Shutdown(SocketShutdown.Both);
     client.Dispose();
 }
        public async Task ReadLineAsync_ThrowsOnConnectionClose()
        {
            TcpListener listener = new TcpListener(IPAddress.Loopback, 0);

            try
            {
                listener.Start();
                Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync();

                TcpClient client = new TcpClient();
                await client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);

                using (TcpClient serverTcpClient = await acceptTask)
                {
                    TcpClientConnectionChannel channel = new TcpClientConnectionChannel(serverTcpClient);
                    client.Dispose();

                    await Assert.ThrowsAsync<ConnectionUnexpectedlyClosedException>(async () =>
                    {
                        await channel.ReadLineAsync();
                    });
                }
            }
            finally
            {
                listener.Stop();
            }
        }
示例#7
0
 public void Dispose()
 {
     _sendQueue.Clear();
     _cts.Cancel();
     _cts?.Dispose();
     _client?.Dispose();
     _stream?.Dispose();
     _streamSemaphore?.Dispose();
 }
示例#8
0
        public void Dispose()
        {
            // NET45's TcpClient only supports a protected Dispose(bool) method so we cannot touch it here
            // The Finalize() call **should** catch that.
#if NET45
#else
            _client.Dispose();
#endif
        }
示例#9
0
 public void Dispose()
 {
     if (isClosed)
     {
         return;
     }
     client.Dispose();
     isClosed = true;
 }
示例#10
0
 public void Dispose()
 {
     if (_stream != null)
     {
         _stream.Dispose();
         _stream = null;
     }
     if (_tcpClient != null)
     {
         _tcpClient.Dispose();
     }
 }
 private void DisposeTcpClient()
 {
     try
     {
         _tcpClient.Close();
         _tcpClient.Dispose();
     }
     catch (Exception ex)
     {
         Debug.WriteLine(string.Format("{0}:  {1}\n{2}", nameof(DisposeTcpClient), ex.Message, ex.StackTrace));
     }
 }
示例#12
0
    static void ProcessRequest(TcpClient socket) {
        HttpServer.Listen(socket, (request) => {
            if (request.RequestUri.Equals(new Utf8String("/plaintext")))
            {
                var formatter = new BufferFormatter(1024, FormattingData.InvariantUtf8);
                HttpWriter.WriteCommonHeaders(formatter, "HTTP/1.1 200 OK");

                formatter.Append("Hello, World!");

                socket.Write(formatter);
                socket.Dispose();
            }
        });
    }
示例#13
0
        public void Dispose()
        {
            if (TokenSource != null)
            {
                if (!TokenSource.IsCancellationRequested)
                {
                    TokenSource.Cancel();
                }
                TokenSource.Dispose();
                TokenSource = null;
            }

            if (_SslStream != null)
            {
                try
                {
                    _SslStream.Close();
                }
                catch (Exception)
                {
                }
            }

            if (_NetworkStream != null)
            {
                try
                {
                    _NetworkStream.Close();
                }
                catch (Exception)
                {
                }
            }

            if (_TcpClient != null)
            {
                try
                {
                    _TcpClient.Close();
                    _TcpClient.Dispose();
                    _TcpClient = null;
                }
                catch (Exception)
                {
                }
            }
        }
        private async void Process(System.Net.Sockets.TcpClient client)
        {
            var clientId = _nextClientId++;

            var wsClient = new WebSocketClient(client)
            {
                Id           = clientId,
                ServerClient = true
            };

            Clients.Add(wsClient);

            OnClientConnected(wsClient);

            try
            {
                //check if it's a websocket connection
                while (client.Connected)
                {
                    if (await ProcessWebsocketUpgrade(wsClient).ConfigureAwait(false))
                    {
                        wsClient.UpgradedConnection = true;
                        break;
                    }
                    else
                    {
                        await Task.Delay(50).ConfigureAwait(false);
                    }
                }

                while (client.IsConnected())
                {
                    var messages = await wsClient.GetMessages().ConfigureAwait(false);

                    ProcessMessage(wsClient, messages);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }

            client?.Dispose();

            Clients.Remove(wsClient);
        }
示例#15
0
 protected override void _Startup()
 {
     try {
         var remoteEp = new IPEndPoint(IPAddress.Parse(remoteIP), remotePort);
         _client = new System.Net.Sockets.TcpClient();
         _client.Connect(remoteEp);
         InvokeRepeating(nameof(_CheckConnectionState), CONN_CHECK_INTERVAL,
                         CONN_CHECK_INTERVAL);
         _packetForwardService.BindReceiver <_TcpClosePacket> (
             _HandleConnectionClosedByRemote);
         base._Startup();
         Connected.Trigger(remoteEp);
     } catch (Exception) {
         _client.Dispose();
         _client = null;
         throw;
     }
 }
示例#16
0
        public void Disconnect()
        {
            try
            {
                if (_tcpClient == null)
                {
                    return;
                }

                _tcpClient.Close();
                _tcpClient.Dispose();
                _tcpClient = null;
            }
            catch
            {
                // ignore
            }
        }
示例#17
0
 private static void Listen(object state)
 {
     if (_listener.Pending())
     {
         Broadcast(_listener, new MessageEventArgs(new Message("Connection Found.")));
         System.Net.Sockets.TcpClient client = (System.Net.Sockets.TcpClient)_listener.AcceptTcpClientAsync().AsyncState;
         if (client != null)
         {
             NetworkStream ns    = client.GetStream();
             byte[]        bytes = new byte[256];
             string        data;
             int           i;
             while ((i = ns.Read(bytes, 0, bytes.Length)) != 0)
             {
                 data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                 Broadcast(_listener, new MessageEventArgs(new Message(data)));
             }
             client.Dispose();
         }
     }
 }
示例#18
0
        /// <summary>
        /// Disconnects from the remote server and cleans up resources
        /// </summary>
        /// <param name="e">An exception if one occurred</param>
        public void Disconnect(Exception e = null)
        {
            if (_client == null)
            {
                return;
            }
            //var remoteEndPoint = _client.Client.RemoteEndPoint.As<IPEndPoint>(); //retain a reference
            _reader?.Stop();
            _reader = null;
            _writer?.Stop();
            _writer = null;
            _networkStream?.Dispose();
            _networkStream = null;
#if NETSTANDARD1_3 || NETSTANDARD1_4
            _client?.Dispose();
#else
            _client?.Close();
#endif
            _client = null;
            OnDisconnected(RemoteEndPoint, e);
        }
示例#19
0
        /// <summary>
        /// Dispose of the TCP client.
        /// </summary>
        /// <param name="disposing">Dispose of resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _Connected = false;

                if (_TokenSource != null)
                {
                    if (!_TokenSource.IsCancellationRequested)
                    {
                        _TokenSource.Cancel();
                    }
                    _TokenSource.Dispose();
                    _TokenSource = null;
                }

                if (_SslStream != null)
                {
                    _SslStream.Close();
                    _SslStream.Dispose();
                    _SslStream = null;
                }

                if (_NetworkStream != null)
                {
                    _NetworkStream.Close();
                    _NetworkStream.Dispose();
                    _NetworkStream = null;
                }

                if (_Client != null)
                {
                    _Client.Close();
                    _Client.Dispose();
                    _Client = null;
                }

                Logger?.Invoke("[SimpleTcp.Client] Dispose complete");
            }
        }
示例#20
0
文件: main.cs 项目: axxu/corefxlab
    static void ProcessRequest(TcpClient socket)
    {
        NetworkStream stream = socket.GetStream();
        byte[] buffer = new byte[1024];
        while(true){
            var read = stream.Read(buffer, 0, buffer.Length);
            Console.WriteLine("\nread {0} bytes:", read);

            if(read > 0) {
                var requestText = Encoding.ASCII.GetString(buffer, 0, read);
                Console.WriteLine(requestText);

                if(requestText.Contains("GET /plaintext")){
                    ProcessPlainTextRequest(socket);
                }
            }
            if (read < buffer.Length)
            {
                break;
            }
        }
        socket.Dispose();
    }
示例#21
0
        /// <summary>
        /// Dispose of the TCP client.
        /// </summary>
        public void Dispose()
        {
            _Connected = false;

            if (_TokenSource != null)
            {
                if (!_TokenSource.IsCancellationRequested)
                {
                    _TokenSource.Cancel();
                }
                _TokenSource.Dispose();
                _TokenSource = null;
            }

            if (_SslStream != null)
            {
                _SslStream.Close();
                _SslStream.Dispose();
                _SslStream = null;
            }

            if (_NetworkStream != null)
            {
                _NetworkStream.Close();
                _NetworkStream.Dispose();
                _NetworkStream = null;
            }

            if (_TcpClient != null)
            {
                _TcpClient.Close();
                _TcpClient.Dispose();
                _TcpClient = null;
            }

            Log("Dispose complete");
        }
示例#22
0
 public void Disconnect()
 {
     connectSocket.Dispose();
 }
        /// <summary>
        /// Establish the connection to the server with retries up to either the timeout specified or the value in Settings.ConnectTimeoutMs.
        /// </summary>
        /// <param name="timeoutMs">The amount of time in milliseconds to continue attempting connections.</param>
        public void ConnectWithRetries(int?timeoutMs = null)
        {
            if (timeoutMs != null && timeoutMs < 1)
            {
                throw new ArgumentException("Timeout milliseconds must be greater than zero.");
            }
            if (timeoutMs != null)
            {
                _Settings.ConnectTimeoutMs = timeoutMs.Value;
            }

            if (IsConnected)
            {
                Logger?.Invoke(_Header + "already connected");
                return;
            }
            else
            {
                Logger?.Invoke(_Header + "initializing client");

                InitializeClient(_Ssl, _PfxCertFilename, _PfxPassword);

                Logger?.Invoke(_Header + "connecting to " + ServerIpPort);
            }

            _TokenSource = new CancellationTokenSource();
            _Token       = _TokenSource.Token;

            CancellationTokenSource connectTokenSource = new CancellationTokenSource();
            CancellationToken       connectToken       = connectTokenSource.Token;

            Task cancelTask  = Task.Delay(_Settings.ConnectTimeoutMs, _Token);
            Task connectTask = Task.Run(() =>
            {
                int retryCount = 0;

                while (true)
                {
                    try
                    {
                        string msg = _Header + "attempting connection to " + _ServerIp + ":" + _ServerPort;
                        if (retryCount > 0)
                        {
                            msg += " (" + retryCount + " retries)";
                        }
                        Logger?.Invoke(msg);

                        _Client.Dispose();
                        _Client = new TcpClient();
                        _Client.ConnectAsync(_ServerIp, _ServerPort).Wait(1000, connectToken);

                        if (_Client.Connected)
                        {
                            Logger?.Invoke(_Header + "connected to " + _ServerIp + ":" + _ServerPort);
                            break;
                        }
                    }
                    catch (TaskCanceledException)
                    {
                        break;
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                    catch (Exception e)
                    {
                        Logger?.Invoke(_Header + "failed connecting to " + _ServerIp + ":" + _ServerPort + ": " + e.Message);
                    }
                    finally
                    {
                        retryCount++;
                    }
                }
            }, connectToken);

            Task.WhenAny(cancelTask, connectTask).Wait();

            if (cancelTask.IsCompleted)
            {
                connectTokenSource.Cancel();
                _Client.Close();
                throw new TimeoutException("Timeout connecting to " + ServerIpPort);
            }

            try
            {
                _NetworkStream = _Client.GetStream();

                if (_Ssl)
                {
                    if (_Settings.AcceptInvalidCertificates)
                    {
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !_Settings.AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }
                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }
                    if (_Settings.MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }

                if (_Keepalive.EnableTcpKeepAlives)
                {
                    EnableKeepalives();
                }
            }
            catch (Exception)
            {
                throw;
            }

            _IsConnected  = true;
            _LastActivity = DateTime.Now;
            _IsTimeout    = false;
            _Events.HandleConnected(this, new ClientConnectedEventArgs(ServerIpPort));
            _DataReceiver      = Task.Run(() => DataReceiver(_Token), _Token);
            _IdleServerMonitor = Task.Run(() => IdleServerMonitor(), _Token);
        }
示例#24
0
 public void Dispose()
 {
     tcpClient?.Dispose();
     stream = null;
 }
示例#25
0
 /// <summary>
 /// Closes out connections to the remote host.
 /// </summary>
 public void Disconnect()
 {
     _stream.Dispose();
     _client.Dispose();
 }
示例#26
0
        private void EnsureConnection()
        {
            do
            {
                lock (thisLock)
                {
                    try
                    {
                        // Make sure we have not already connnected on another thread
                        if (_client != null && _client.Connected)
                            return;

                        // Clean up anything that is outstanding
                        if (_client != null)
                        {
                            //_client.Client.Shutdown(SocketShutdown.Both);
                            _client.Dispose();
                        }

                        MyLogger.LogInfo("Reconnecting the socket");
                        _client = new TcpClient();
                        Task ca = _client.ConnectAsync(Host, Port);
                        if (ca.Wait(15000) == false)
                        {
                            MyLogger.LogError($"ERROR: Could not connect within 15 seconds to {Host} on Port {Port}");
                        }

                        // Return if we connected properly
                        if (_client.Connected)
                            return;

                        _client.Dispose();
                        _client = null;
                        MyLogger.LogError($"ERROR: Could not connect to {Host} on Port {Port}");
                    }
                    catch (Exception ex)
                    {
                        MyLogger.LogError($"ERROR: trying to connect {Host} on Port {Port} - {MyLogger.ExMsg(ex)}");
                        _client = null;
                    }

                    // Wait 5 seconds before trying to re-connect
                    MyLogger.LogInfo("Waiting 5 seconds before trying to re-connect");
                    Thread.Sleep(5000);
                }

            } while (_client == null);
        }
示例#27
0
        void ExecuteRequest(TcpClient client)
        {
            // By default we will close the stream to cater for failure scenarios
            var keepStreamOpen = false;

            var clientName = client.Client.RemoteEndPoint;
            var stream = client.GetStream();

            using (var ssl = new SslStream(stream, true, AcceptAnySslCertificate))
            {
                try
                {
                    log.Write(EventType.Security, "Performing TLS server handshake");
                    ssl.AuthenticateAsServerAsync(serverCertificate, true, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false).GetAwaiter().GetResult();

                    log.Write(EventType.Security, "Secure connection established, client is not yet authenticated, client connected with {0}", ssl.SslProtocol.ToString());

                    var req = ReadInitialRequest(ssl);
                    if (string.IsNullOrEmpty(req))
                    {
                        log.Write(EventType.Diagnostic, "Ignoring empty request");
                        return;
                    }

                    if (req.Substring(0, 2) != "MX")
                    {
                        log.Write(EventType.Diagnostic, "Appears to be a web browser, sending friendly HTML response");
                        SendFriendlyHtmlPage(ssl);
                        return;
                    }

                    if (Authorize(ssl, clientName))
                    {
                        // Delegate the open stream to the protocol handler - we no longer own the stream lifetime
                        ExchangeMessages(ssl);

                        // Mark the stream as delegated once everything has succeeded
                        keepStreamOpen = true;
                    }
                }
                catch (AuthenticationException ex)
                {
                    log.WriteException(EventType.ClientDenied, "Client failed authentication: {0}", ex, clientName);
                }
                catch (Exception ex)
                {
                    log.WriteException(EventType.Error, "Unhandled error when handling request from client: {0}", ex, clientName);
                }
                finally
                {
                    if (!keepStreamOpen)
                    {
                        // Closing an already closed stream or client is safe, better not to leak
#if NET40
                        stream.Close();
                        client.Close();
#else
                        stream.Dispose();
                        client.Dispose();
#endif
                    }
                }
            }
        }
示例#28
0
 public void Dispose()
 {
     Socket.Dispose();
 }
        private void Cleanup(TcpClient tcpClient)
        {
            if (tcpClient != null)
            {
                try
                {
                    // close the connection
            #if NET_CORE
                    tcpClient.Dispose();
            #endif
            #if NET_45
                    tcpClient.Close();
            #endif
                }
            #if !NET_CORE
                catch (IOException e)
                {
                    if (LOG.IsDebugEnabled)
                        LOG.Debug("Ignoring exception during channel close", e);
                }
            #endif
            #if NET_CORE
                catch (Exception e)
                {
                }
            #endif
            }

            lock (outgoingQueue)
            {
                foreach (var packet in outgoingQueue)
                {
                    ConLossPacket(packet);
                }
                outgoingQueue.Clear();
            }

            Packet pack;
            while (pendingQueue.TryDequeue(out pack))
                ConLossPacket(pack);
        }
示例#30
0
 public void Dispose()
 {
     _networkStream?.Dispose();
     _client?.Dispose();
 }
示例#31
0
 public void Dispose()
 {
     _client.Dispose();
 }
示例#32
0
        private void EnsureConnection()
        {
            do
            {
                lock (thisLock)
                {
                    if (_client != null && _client.Connected)
                    {
                        // Already connected
                        return;
                    }

                    // Clean up anything that is outstanding
                    if (_client != null)
                    {
                        //_client.Client.Shutdown(SocketShutdown.Both);
                        _client.Dispose();
                    }

                    _client = new TcpClient();
                    Task ca = _client.ConnectAsync(hubAddress, hubPort);
                    if (ca.Wait(15000) == false)
                    {
                        // Could not connect within 15 seconds
                        return;
                    }

                    // Make sure it connected properly
                    if (_client.Connected)
                        return;

                    // No good, it will retry shortly
                    _client.Dispose();
                    _client = null;
                }
            } while (_client == null);
        }
示例#33
0
        public async Task <byte[]> SendMessage(byte[] message,
                                               CancellationToken cancellationToken = default(CancellationToken))
        {
            await Task.Yield();

            var result = default(byte[]);

            try
            {
                //query the server
                using (var client = new System.Net.Sockets.TcpClient(AddressFamily.InterNetwork))
                {
                    client.Client.NoDelay = true;

                    if (!cancellationToken.IsCancellationRequested)
                    {
                        await client.ConnectAsync(ServerConnection.Host, ServerConnection.Port);

                        if (!cancellationToken.IsCancellationRequested)
                        {
                            using (var stream = client.GetStream())
                            {
                                if (PacketFormatter != null)
                                {
                                    message = PacketFormatter.AddFooter(message);
                                }

                                if (!cancellationToken.IsCancellationRequested)
                                {
                                    await stream.WriteAsync(message, 0, message.Length);

                                    await stream.FlushAsync();

                                    if (!cancellationToken.IsCancellationRequested)
                                    {
                                        using (var memoryStream = new MemoryStream())
                                        {
                                            var readBuffer = new byte[32768];
                                            while (true)
                                            {
                                                var read = await stream.ReadAsync(readBuffer, 0, readBuffer.Length);

                                                if (read > 0)
                                                {
                                                    await memoryStream.WriteAsync(readBuffer, 0, read);
                                                }
                                                if (read <= 0 || readBuffer[read - 1] == 4)
                                                {
                                                    var data = memoryStream.ToArray();
                                                    if (PacketFormatter != null)
                                                    {
                                                        result = PacketFormatter.RemoveFooter(data);
                                                    }
                                                    else
                                                    {
                                                        result = data;
                                                    }
                                                    break;
                                                }
                                            }

                                            memoryStream.Close();
                                            memoryStream.Dispose();
                                        }
                                    }

                                    stream.Close();
                                    stream.Dispose();
                                }
                            }
                        }

                        client.Close();
                        client.Dispose();
                    }
                }
            }
            catch (Exception)
            {
            }

            return(result);
        }
示例#34
0
文件: Conn.cs 项目: nats-io/csnats
            internal void closeClient(TcpClient c)
            {
                if (c != null)
                {
#if NET45
                    c.Close();
#else
                    c.Dispose();
#endif
                }
            }