Dispose() public method

public Dispose ( ) : void
return void
        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();
            }
        }
 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();
 }
        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
            }

        }
Example #4
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();
            }
        });
    }
Example #5
0
    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();
    }
Example #6
0
            internal void closeClient(TcpClient c)
            {
                if (c != null)
                {
#if NET45
                    c.Close();
#else
                    c.Dispose();
#endif
                }
            }
Example #7
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
                    }
                }
            }
        }
Example #8
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);
        }
        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);
        }
Example #10
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);
        }