当前位置: 首页>>代码示例>>C#>>正文


C# TcpClient.Dispose方法代码示例

本文整理汇总了C#中System.Net.Sockets.TcpClient.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# TcpClient.Dispose方法的具体用法?C# TcpClient.Dispose怎么用?C# TcpClient.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.TcpClient的用法示例。


在下文中一共展示了TcpClient.Dispose方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ReadLineAsync_ThrowsOnConnectionClose

        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();
            }
        }
开发者ID:rnwood,项目名称:smtp4dev,代码行数:28,代码来源:TcpClientConnectionChannelTests.cs

示例2: SendHttpResponse

 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();
 }
开发者ID:LindaLawton,项目名称:google-api-dotnet-client,代码行数:32,代码来源:HttpListener.cs

示例3: Send

        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
            }

        }
开发者ID:neutmute,项目名称:loggly-csharp,代码行数:26,代码来源:SyslogTcpTransport.cs

示例4: ProcessRequest

    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();
            }
        });
    }
开发者ID:TerabyteX,项目名称:corefxlab,代码行数:14,代码来源:main.cs

示例5: ProcessRequest

    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();
    }
开发者ID:axxu,项目名称:corefxlab,代码行数:23,代码来源:main.cs

示例6: closeClient

            internal void closeClient(TcpClient c)
            {
                if (c != null)
                {
#if NET45
                    c.Close();
#else
                    c.Dispose();
#endif
                }
            }
开发者ID:nats-io,项目名称:csnats,代码行数:11,代码来源:Conn.cs

示例7: ExecuteRequest

        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
                    }
                }
            }
        }
开发者ID:OctopusDeploy,项目名称:Halibut,代码行数:64,代码来源:SecureListener.cs

示例8: EnsureConnection

        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);
        }
开发者ID:joejarvis64,项目名称:j64.AlarmServer,代码行数:48,代码来源:TPISocket.cs

示例9: Cleanup

        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);
        }
开发者ID:GamesDesignArt,项目名称:DotnetSpider,代码行数:41,代码来源:ClientConnectionRequestProducer.cs

示例10: EnsureConnection

        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);
        }
开发者ID:joejarvis64,项目名称:j64.Harmony,代码行数:37,代码来源:Hub.cs


注:本文中的System.Net.Sockets.TcpClient.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。