System.Net.Sockets.TcpClient.Close()

Here are the examples of the csharp api System.Net.Sockets.TcpClient.Close() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

515 Examples 7

19 Source : Controller.cs
with MIT License
from ctsecurity

private void disconnectButton_Click(object sender, EventArgs e)
        {
            if (client.Visible)
                client.Dispose();
            connector.Close();
            showConnect();
        }

19 Source : Controller.cs
with MIT License
from ctsecurity

public void screenClosed()
        {
            if (client.Visible)
                client.Dispose();
            connector.Close();
            showConnect();
        }

19 Source : SocketFrameHandler.cs
with MIT License
from CymaticLabs

private void Connect(TcpClient 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();
            }
        }

19 Source : SocketFrameHandler.cs
with MIT License
from CymaticLabs

public void Close()
        {
            lock (m_semapreplaced)
            {
                if (!m_closed)
                {
                    m_socket.LingerState = new LingerOption(true, SOCKET_CLOSING_TIMEOUT);
                    m_socket.Close();
                    m_closed = true;
                }
            }
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

private void ReceiveThreadFunction(string ip, int port)
        {
            try
            {
                client.Connect(ip, port);
                _Connecting = false;

                sendThread = new Thread(() => { SendLoop(0, client, sendQueue, sendPending); });
                sendThread.IsBackground = true;
                sendThread.Start();

                ReceiveLoop(0, client, receiveQueue, MaxMessageSize);
            }
            catch (SocketException exception)
            {
                Logger.Log("Client Recv: failed to connect to ip=" + ip + " port=" + port + " reason=" + exception);

                receiveQueue.Enqueue(new Message(0, EventType.Disconnected, null));
            }
            catch (Exception exception)
            {
                Logger.LogError("Client Recv Exception: " + exception);
            }

            sendThread?.Interrupt();

            _Connecting = false;

            client.Close();
        }

19 Source : Client.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

public void Disconnect()
        {
            if (Connecting || Connected)
            {
                client.Close();

                receiveThread?.Join();

                sendQueue.Clear();

                client = null;
            }
        }

19 Source : Common.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

protected static void ReceiveLoop(int connectionId, TcpClient client, ConcurrentQueue<Message> receiveQueue,
            int MaxMessageSize)
        {
            NetworkStream stream = client.GetStream();

            DateTime messageQueueLastWarning = DateTime.Now;

            try
            {
                receiveQueue.Enqueue(new Message(connectionId, EventType.Connected, null));

                while (true)
                {
                    byte[] content;
                    if (!ReadMessageBlocking(stream, MaxMessageSize, out content))
                        break;

                    receiveQueue.Enqueue(new Message(connectionId, EventType.Data, content));

                    if (receiveQueue.Count > messageQueueSizeWarning)
                    {
                        TimeSpan elapsed = DateTime.Now - messageQueueLastWarning;
                        if (elapsed.TotalSeconds > 10)
                        {
                            Logger.LogWarning("ReceiveLoop: messageQueue is getting big(" + receiveQueue.Count +
                                              "), try calling GetNextMessage more often. You can call it more than once per frame!");
                            messageQueueLastWarning = DateTime.Now;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Log("ReceiveLoop: finished receive function for connectionId=" + connectionId + " reason: " +
                           exception);
            }

            stream.Close();
            client.Close();

            receiveQueue.Enqueue(new Message(connectionId, EventType.Disconnected, null));
        }

19 Source : Server.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

public void Stop()
        {
            if (!Active) return;

            Logger.Log("Server: stopping...");

            listener?.Stop();

            listenerThread?.Interrupt();
            listenerThread = null;

            foreach (KeyValuePair<int, ClientToken> kvp in clients)
            {
                TcpClient client = kvp.Value.client;
                try
                {
                    client.GetStream().Close();
                }
                catch { }

                client.Close();
            }

            clients.Clear();
        }

19 Source : Server.cs
with BSD 3-Clause "New" or "Revised" License
from DannyTheSloth

public bool Disconnect(int connectionId)
        {
            ClientToken token;
            if (clients.TryGetValue(connectionId, out token))
            {
                token.client.Close();
                Logger.Log("Server.Disconnect connectionId:" + connectionId);
                return true;
            }

            return false;
        }

19 Source : TcpListenerWebSocketContext.cs
with Apache License 2.0
from decentraland

internal void Close()
        {
            _stream.Close();
            _tcpClient.Close();
        }

19 Source : TcpListenerWebSocketContext.cs
with Apache License 2.0
from decentraland

internal void Close(HttpStatusCode code)
        {
            var res = HttpResponse.CreateCloseResponse(code);
            var bytes = res.ToByteArray();
            _stream.Write(bytes, 0, bytes.Length);

            _stream.Close();
            _tcpClient.Close();
        }

19 Source : InternetDiagnosticsTool.cs
with GNU General Public License v3.0
from DeepView

public static bool CheckNetworkWithTcpFeedback(string targetHost)
      {
         bool result = true;
         try
         {
            TcpClient client = new TcpClient(targetHost, 80);
            client.Close();
         }
         catch (Exception throwedException) { if (throwedException != null) result = false; }
         return result;
      }

19 Source : WebSocketServer.cs
with GNU General Public License v3.0
from denniskrupke

private void receiveRequest ()
    {
      while (true) {
        try {
          var cl = _listener.AcceptTcpClient ();
          ThreadPool.QueueUserWorkItem (
            state => {
              try {
                var ctx = cl.GetWebSocketContext (null, _secure, _sslConfig, _logger);
                if (_authSchemes != AuthenticationSchemes.Anonymous &&
                    !authenticate (ctx, _authSchemes, Realm, UserCredentialsFinder))
                  return;

                processRequest (ctx);
              }
              catch (Exception ex) {
                _logger.Fatal (ex.ToString ());
                cl.Close ();
              }
            });
        }
        catch (SocketException ex) {
          _logger.Warn ("Receiving has been stopped.\n  reason: " + ex.Message);
          break;
        }
        catch (Exception ex) {
          _logger.Fatal (ex.ToString ());
          break;
        }
      }

      if (IsListening)
        abort ();
    }

19 Source : ServiceRunner.cs
with GNU Affero General Public License v3.0
from devunt

internal async Task Run()
        {
            var certificate = CertificateBuilder.Build(Attribute.Hostname);
            var listener = new TcpListener(IPAddress.Loopback, Attribute.Port);
            listener.Start();

            Log.I($"[{Identifier}:{Attribute.Type}] Listening on {Attribute.Hostname}:{Attribute.Port}");

            while (true)
            {
                // Log.D($"[{Identifier}] Waiting for new connection");
                var client = await listener.AcceptTcpClientAsync();
                // Log.D($"[{Identifier}] Got connection from {client.Client.RemoteEndPoint}");
                var sslStream = new SslStream(client.GetStream(), false);
                try
                {
                    await sslStream.AuthenticatereplacederverAsync(certificate, false, SslProtocols.Tls12, false);
                    sslStream.ReadTimeout = 5000;
                    sslStream.WriteTimeout = 5000;

                    using (var reader = new StreamReader(sslStream))
                    {
                        IAsyncEnumerator<byte[]> responses = null;

                        switch (Attribute.Type)
                        {
                            case HandlerType.Http:
                                responses = HandleHttpRequest(reader);
                                break;
                            case HandlerType.Ws:
                                responses = HandleWsRequest(reader);
                                break;
                        }

                        try
                        {
                            await responses.ForEachAsync(
                                async response => await sslStream.WriteAsync(response, 0, response.Length));
                        }
                        catch (TaskCanceledException) { }
                    }
                }
                catch (Exception ex)
                {
                    Log.Ex(ex, $"Exception occured while handling request on {Identifier} ");
                }
                finally
                {
                    sslStream.Dispose();
                    client.Close();
                }
            }
        }

19 Source : TcpReaderUtil.cs
with GNU Lesser General Public License v3.0
from DigiByteMiner

public string GetData(string command)
        {
            int timeoutInMS = 1000;

            string output = "";
            Stream s = default(Stream);
            TcpClient tcpClient = default(TcpClient);

            try
            {
                tcpClient = new TcpClient();
                tcpClient.SendTimeout = timeoutInMS;
                tcpClient.ReceiveTimeout = timeoutInMS;
                tcpClient.Connect(IP, int.Parse(Port));
                s = tcpClient.GetStream();
                if (s != null)
                {
                    StreamReader sr = new StreamReader(s);
                    StreamWriter sw = new StreamWriter(s);
                    sw.AutoFlush = true;

                    //sw.WriteLine("summary");
                    sw.WriteLine(command);

                    output = sr.ReadToEnd();
                }

            }
            catch(Exception e)
            {
                Logger.Instance.LogError("TcpReaderUtil::GetData: " + e.ToString());
            }
            finally
            {
                tcpClient.Close();
                if (s != null)
                {
                    s.Close();
                }
            }
            return output;
        }

19 Source : MailDemonService_Tls.cs
with MIT License
from DigitalRuby

private async Task<Tuple<SslStream, Stream, StreamWriter>> StartTls
        (
            TcpClient tcpClient,
            string clientIPAddress,
            Stream reader,
            StreamWriter writer,
            bool sendReadyCommand,
            X509Certificate2 sslCertificate)
        {
            if (sslCertificate == null)
            {
                await writer.WriteLineAsync("501 Syntax error (no parameters allowed)");
                await writer.FlushAsync();
                return null;
            }
            else if (sendReadyCommand)
            {
                // upgrade to ssl
                await writer.WriteLineAsync($"220 Ready to start TLS");
                await writer.FlushAsync();
            }

            // create ssl stream and ensure encryption is required
            SslStream sslStream = new SslStream(reader, false, null, null, EncryptionPolicy.RequireEncryption);

            try
            {
                bool sslServerEnabled = false;

                // shut everything down after 5 seconds if not success
                Task.Run(async () =>
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    if (!sslServerEnabled)
                    {
                        try
                        {
                            sslStream.Close();
                            tcpClient.Close();
                        }
                        catch
                        {
                        }
                    }
                }).ConfigureAwait(false).GetAwaiter();
                MailDemonLog.Info($"Starting ssl connection from client {clientIPAddress}");
                await sslStream.AuthenticatereplacederverAsync(sslCertificate, false, System.Security.Authentication.SslProtocols.Tls12 |
                    System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls, true);
                sslServerEnabled = true;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Unable to negotiate ssl from client {clientIPAddress}, error: {ex}");
            }

            // create comm streams on top of ssl stream
            Stream sslReader = sslStream;
            StreamWriter sslWriter = new StreamWriter(sslStream, MailDemonExtensionMethods.Utf8EncodingNoByteMarker) { AutoFlush = true, NewLine = "\r\n" };

            return new Tuple<SslStream, Stream, StreamWriter>(sslStream, sslReader, sslWriter);
        }

19 Source : DroneRPC.cs
with MIT License
from dji-sdk

public void ConnectToIotEdge(string TagertIP, int TagertPort)
        {

            IPAddress address = IPAddress.Parse(TagertIP);

            TcpClient client = new TcpClient();

            client.Connect(address, TagertPort);

            NetworkStream ns = client.GetStream();

            string Sendmessage = M_port.ToString();


            Byte[] sendBytes = Encoding.UTF8.GetBytes(Sendmessage);
            ns.Write(sendBytes, 0, sendBytes.Length);

            ns.Close();
            client.Close();
        }

19 Source : Connection.cs
with GNU General Public License v3.0
from dkuwahara

protected void OnTerminate()
        {
            _tcpClient.Close();
            _stream.Close();
        }

19 Source : Resolver.cs
with BSD 2-Clause "Simplified" License
from double-hi

private DNSResponse TcpRequest(DNSRequest request, List<IPEndPoint> dnsServers, int timeout)
        {
            //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            //sw.Start();

            byte[] responseMessage = new byte[512];

            for (int intAttempts = 0; intAttempts < m_Retries; intAttempts++)
            {
                for (int intDnsServer = 0; intDnsServer < dnsServers.Count; intDnsServer++)
                {
                    var tcpClient = new TcpClient
                    {
                        ReceiveTimeout = timeout * 1000
                    };

                    try
                    {
                        IAsyncResult result = tcpClient.BeginConnect(dnsServers[intDnsServer].Address, dnsServers[intDnsServer].Port, null, null);

                        bool success = result.AsyncWaitHandle.WaitOne(timeout * 1000, true);

                        if (!success || !tcpClient.Connected)
                        {
                            tcpClient.Close();
                            Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
                            continue;
                        }

                        BufferedStream bs = new BufferedStream(tcpClient.GetStream());

                        byte[] data = request.Data;
                        bs.WriteByte((byte)((data.Length >> 8) & 0xff));
                        bs.WriteByte((byte)(data.Length & 0xff));
                        bs.Write(data, 0, data.Length);
                        bs.Flush();

                        DNSResponse TransferResponse = new DNSResponse();
                        int intSoa = 0;
                        int intMessageSize = 0;

                        //Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS");

                        while (true)
                        {
                            int intLength = bs.ReadByte() << 8 | bs.ReadByte();
                            if (intLength <= 0)
                            {
                                tcpClient.Close();
                                Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
                                throw new SocketException(); // next try
                            }

                            intMessageSize += intLength;

                            data = new byte[intLength];
                            bs.Read(data, 0, intLength);
                            DNSResponse response = new DNSResponse(dnsServers[intDnsServer], data);

                            //Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS");

                            if (response.header.RCODE != RCode.NOERROR)
                                return response;

                            if (response.Questions[0].QType != DNSQType.AXFR)
                            {
                                //AddToCache(response);
                                return response;
                            }

                            // Zone transfer!!

                            if (TransferResponse.Questions.Count == 0)
                                TransferResponse.Questions.AddRange(response.Questions);
                            TransferResponse.Answers.AddRange(response.Answers);
                            TransferResponse.Authorities.AddRange(response.Authorities);
                            TransferResponse.Additionals.AddRange(response.Additionals);

                            if (response.Answers[0].Type == DNSType.SOA)
                                intSoa++;

                            if (intSoa == 2)
                            {
                                TransferResponse.header.QDCOUNT = (ushort)TransferResponse.Questions.Count;
                                TransferResponse.header.ANCOUNT = (ushort)TransferResponse.Answers.Count;
                                TransferResponse.header.NSCOUNT = (ushort)TransferResponse.Authorities.Count;
                                TransferResponse.header.ARCOUNT = (ushort)TransferResponse.Additionals.Count;
                                TransferResponse.MessageSize = intMessageSize;
                                return TransferResponse;
                            }
                        }
                    } // try
                    catch (SocketException)
                    {
                        continue; // next try
                    }
                    finally
                    {
                        m_Unique++;

                        // close the socket
                        tcpClient.Close();
                    }
                }
            }
            DNSResponse responseTimeout = new DNSResponse
            {
                Timedout = true
            };
            return responseTimeout;
        }

19 Source : RTSPClient.cs
with BSD 2-Clause "Simplified" License
from double-hi

public string GetStreamDescription(string url)
        {
            try
            {
                string hostname = Regex.Match(url, @"rtsp://(?<hostname>\S+?)/").Result("${hostname}");
                //IPEndPoint rtspEndPoint = DNSResolver.R(hostname, DNS_RESOLUTION_TIMEOUT);

                logger.Debug("RTSP Client Connecting to " + hostname + ".");
                TcpClient rtspSocket = new TcpClient(hostname, RTSP_PORT);
                NetworkStream rtspStream = rtspSocket.GetStream();

                string rtspSDP = null;
                RTSPRequest rtspRequest = new RTSPRequest(RTSPMethodsEnum.DESCRIBE, url);
                RTSPHeader rtspHeader = new RTSPHeader(1, null);
                rtspRequest.Header = rtspHeader;
                string rtspReqStr = rtspRequest.ToString();

                RTSPMessage rtspMessage = null;
                RTSPResponse rtspResponse = null;

                byte[] rtspRequestBuffer = Encoding.UTF8.GetBytes(rtspReqStr);
                rtspStream.Write(rtspRequestBuffer, 0, rtspRequestBuffer.Length);

                byte[] buffer = new byte[2048];
                int bytesRead = rtspStream.Read(buffer, 0, 2048);

                if (bytesRead > 0)
                {
                    logger.Debug(Encoding.UTF8.GetString(buffer, 0, bytesRead));
                    byte[] msgBuffer = new byte[bytesRead];
                    Buffer.BlockCopy(buffer, 0, msgBuffer, 0, bytesRead);
                    rtspMessage = RTSPMessage.ParseRTSPMessage(msgBuffer, null, null);

                    if (rtspMessage.RTSPMessageType == RTSPMessageTypesEnum.Response)
                    {
                        rtspResponse = RTSPResponse.ParseRTSPResponse(rtspMessage);
                        logger.Debug("RTSP Response received: " + rtspResponse.StatusCode + " " + rtspResponse.Status + " " + rtspResponse.ReasonPhrase + ".");
                    }

                    rtspSDP = rtspResponse.Body;
                }
                else
                {
                    logger.Warn("Socket closed prematurely in GetStreamDescription for " + url + ".");
                }

                rtspSocket.Close();

                return rtspSDP;
            }
            catch (Exception excp)
            {
                logger.Error("Exception GetStreamDescription. " + excp.Message);
                throw excp;
            }
        }

19 Source : SIPConnection.cs
with BSD 2-Clause "Simplified" License
from double-hi

public void Close()
        {
            try
            {
                if (_tcpClient.GetStream() != null)
                {
                    _tcpClient.GetStream().Close(0);
                }

                if (_tcpClient.Client != null && _tcpClient.Client.Connected == true)
                {
                    _tcpClient.Client.Shutdown(SocketShutdown.Both);
                    _tcpClient.Client.Close(0);
                }

                _tcpClient.Close();
            }
            catch (Exception closeExcp)
            {
                logger.Warn("Exception closing socket in SIPConnection Close. " + closeExcp.Message);
            }
        }

19 Source : SIPTLSChannel.cs
with BSD 2-Clause "Simplified" License
from double-hi

private void EndConnect(IAsyncResult ar)
        {
            object[] stateObj = (object[])ar.AsyncState;
            TcpClient tcpClient = (TcpClient)stateObj[0];
            IPEndPoint dstEndPoint = (IPEndPoint)stateObj[1];
            byte[] buffer = (byte[])stateObj[2];
            string serverCN = (string)stateObj[3];

            try
            {
                m_connectingSockets.Remove(dstEndPoint.ToString());

                tcpClient.EndConnect(ar);

                SslStream sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                //DisplayCertificateInformation(sslStream);

                 SIPConnection callerConnection = new SIPConnection(this, tcpClient, sslStream, dstEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Caller);
                 sslStream.BeginAuthenticateAsClient(serverCN, EndAuthenticateAsClient, new object[] { tcpClient, dstEndPoint, buffer, callerConnection });
                //sslStream.AuthenticateAsClient(serverCN);

                //if (tcpClient != null && tcpClient.Connected)
                //{
                //    SIPConnection callerConnection = new SIPConnection(this, sslStream, dstEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Caller);
                //    m_connectedSockets.Add(dstEndPoint.ToString(), callerConnection);

                //    callerConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
                //    callerConnection.SIPMessageReceived += SIPTLSMessageReceived;
                //    //byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
                //    callerConnection.SIPStream.BeginRead(callerConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), callerConnection);

                //    logger.Debug("Established TLS connection to " + dstEndPoint + ".");

                //    callerConnection.SIPStream.BeginWrite(buffer, 0, buffer.Length, EndSend, callerConnection);
                //}
                //else
                //{
                //    logger.Warn("Could not establish TLS connection to " + dstEndPoint + ".");
                //}
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPTLSChannel EndConnect. " + excp);

                if(tcpClient != null)
                {
                    try
                    {
                        tcpClient.Close();
                    }
                    catch(Exception closeExcp)
                    {
                        logger.Warn("Exception SIPTLSChannel EndConnect Close TCP Client. " + closeExcp);
                    }
                }
            }
        }

19 Source : ImpServer.cs
with GNU General Public License v3.0
from DouglasDwyer

private void AcceptTcpClient(IAsyncResult result)
        {
            TcpClient client = Listener.EndAcceptTcpClient(result);
            Listener.BeginAcceptTcpClient(AcceptTcpClient, null);
            try
            {
                if (ActiveClients.Count >= MaximumConnectedClients)
                {
                    client.Close();
                }
                else
                {
                    BinaryWriter writer = new BinaryWriter(client.GetStream());
                    BinaryReader reader = new BinaryReader(client.GetStream());//BadProxyBinder.Instance.GetRemoteClreplaced(ShareAsAttribute.ProxyIndex[reader.ReadUInt16()]);
                    ImpClient kClient = null;
                    ActiveClients.Add(x =>
                    {
                        ushort networkID = (ushort)(x + 1);
                        ImpPowerSerializer serializer = (ImpPowerSerializer)DefaultSerializer.Clone();
                        kClient = new ImpClient(client, this, networkID, DefaultMaximumHeldObjects, DefaultMaximumRemoteObjects, UnreliableListener, DefaultProxyBinder, serializer, DefaultRemoteTaskScheduler);
                        CheckClientType(kClient.RemoteClient.GetType());
                        return kClient.RemoteClient;
                    });
                    OnClientConnected(kClient.RemoteClient);
                }
            }
            catch(Exception e)
            {
                OnClientNetworkError(null, e);
            }
        }

19 Source : ImpClient.cs
with GNU General Public License v3.0
from DouglasDwyer

private void ProcessDisconnection()
        {
            lock (Locker)
            {
                try
                {
                    InternalClient.Close();
                }
                catch { }
                try
                {
                    if (Local)
                    {
                        UnreliableClient.Close();
                    }
                }
                catch { }

                foreach(AsynchronousNetworkOperation operation in CurrentNetworkOperations.Values)
                {
                    operation.SetException(new IOException("The client was disconnected while processing this network operation."), RemoteTaskScheduler);
                }
                foreach(CountedObject<WeakReference<RemoteSharedObject>> rem in RemoteSharedObjects.Values)
                {
                    RemoteSharedObject obj;
                    if(rem.ReferencedObject.TryGetTarget(out obj))
                    {
                        obj.HostClient = null;
                    }
                }
                CurrentNetworkOperations = new IdentifiedCollection<AsynchronousNetworkOperation>();
                HeldObjects = new IdentifiedCollection<object>();
                HeldObjectsData.Clear();
                RemoteSharedObjects.Clear();

                Connected = false;
                InternalClient = null;
            }
        }

19 Source : TestSMTPServer.cs
with GNU General Public License v3.0
from DSorlov

protected override void ProcessRecord()
        {
            if (ShouldProcess(serverName, "Check mailserver"))
            {
                IPAddress address;
                IPAddress[] addresses = new IPAddress[] { };
                if (IPAddress.TryParse(serverName,out address))
                {
                    WriteVerbose(string.Format("{0} is a IP, will not look up. Proceeding to connection test..",serverName));
                    addresses = new IPAddress[] { address };
                }
                else
                {
                    WriteVerbose(string.Format("{0} is not a IP, will now look it up..",serverName));
                    try { addresses = System.Net.Dns.GetHostAddresses(serverName); }
                    catch { }
                    WriteVerbose(string.Format("Found {0} matches to that hostname..",addresses.Length));
                }

                if (addresses.Length < 1)
                {
                    WriteObject(new SMTPConversationResult("Mailserver hostname could not be resolved", false, TimeSpan.Zero,senderName,recipientName,serverName));
                }
                else
                {
                    foreach(IPAddress host in addresses)
                    {
                            TcpClient client = new TcpClient(host.AddressFamily);
                            DateTime startTime = DateTime.Now;
                            IAsyncResult clientConnect = client.BeginConnect(host, serverPort, null, null);
                            clientConnect.AsyncWaitHandle.WaitOne(1000, false);

                            if (client.Connected)
                            {
                                NetworkStream stream = client.GetStream();
                                StreamReader reader = new StreamReader(stream);
                                StreamWriter writer = new StreamWriter(stream);

                                Thread.Sleep(500);
                                SMTPConversationResult result = SMTPTalker(startTime,reader, writer, host.ToString());
                                WriteObject(result);

                                writer.Close();
                                reader.Close();
                                client.Close();
                            }
                            else
                                WriteObject(new SMTPConversationResult("Connection timed out", false, TimeSpan.Zero,senderName,recipientName,host.ToString()));
                        
                        
                        


                    }
                }
            }



        }

19 Source : Resolver.cs
with GNU General Public License v3.0
from DSorlov

private Response TcpRequest(Request request)
		{
			//System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
			//sw.Start();

			byte[] responseMessage = new byte[512];

			for (int intAttempts = 0; intAttempts < m_Retries; intAttempts++)
			{
				for (int intDnsServer = 0; intDnsServer < m_DnsServers.Count; intDnsServer++)
				{
					TcpClient tcpClient = new TcpClient();
					tcpClient.ReceiveTimeout = m_Timeout * 1000;

					try
					{
						IAsyncResult result = tcpClient.BeginConnect(m_DnsServers[intDnsServer].Address, m_DnsServers[intDnsServer].Port, null, null);

						bool success = result.AsyncWaitHandle.WaitOne(m_Timeout*1000, true);

						if (!success || !tcpClient.Connected)
						{
							tcpClient.Close();
							Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
							continue;
						}

						BufferedStream bs = new BufferedStream(tcpClient.GetStream());

						byte[] data = request.Data;
						bs.WriteByte((byte)((data.Length >> 8) & 0xff));
						bs.WriteByte((byte)(data.Length & 0xff));
						bs.Write(data, 0, data.Length);
						bs.Flush();

						Response TransferResponse = new Response();
						int intSoa = 0;
						int intMessageSize = 0;

						//Debug.WriteLine("Sending "+ (request.Length+2) + " bytes in "+ sw.ElapsedMilliseconds+" mS");

						while (true)
						{
							int intLength = bs.ReadByte() << 8 | bs.ReadByte();
							if (intLength <= 0)
							{
								tcpClient.Close();
								Verbose(string.Format(";; Connection to nameserver {0} failed", (intDnsServer + 1)));
								throw new SocketException(); // next try
							}

							intMessageSize += intLength;

							data = new byte[intLength];
							bs.Read(data, 0, intLength);
							Response response = new Response(m_DnsServers[intDnsServer], data);

							//Debug.WriteLine("Received "+ (intLength+2)+" bytes in "+sw.ElapsedMilliseconds +" mS");

							if (response.header.RCODE != RCode.NoError)
								return response;

							if (response.Questions[0].QType != QType.AXFR)
							{
								AddToCache(response);
								return response;
							}

							// Zone transfer!!

							if(TransferResponse.Questions.Count==0)
								TransferResponse.Questions.AddRange(response.Questions);
							TransferResponse.Answers.AddRange(response.Answers);
							TransferResponse.Authorities.AddRange(response.Authorities);
							TransferResponse.Additionals.AddRange(response.Additionals);

							if (response.Answers[0].Type == Type.SOA)
									intSoa++;

							if (intSoa == 2)
							{
								TransferResponse.header.QDCOUNT = (ushort)TransferResponse.Questions.Count;
								TransferResponse.header.ANCOUNT = (ushort)TransferResponse.Answers.Count;
								TransferResponse.header.NSCOUNT = (ushort)TransferResponse.Authorities.Count;
								TransferResponse.header.ARCOUNT = (ushort)TransferResponse.Additionals.Count;
								TransferResponse.MessageSize = intMessageSize;
								return TransferResponse;
							}
						}
					} // try
					catch (SocketException)
					{
						continue; // next try
					}
					finally
					{
						m_Unique++;

						// close the socket
						tcpClient.Close();
					}
				}
			}
			Response responseTimeout = new Response();
			responseTimeout.Error = "Timeout Error";
			return responseTimeout;
		}

19 Source : TcpClient.cs
with MIT License
from dust63

public void Disconnect()
        {
            if (_tcpClient == null)
                return;

            _readTimer.Dispose();
            _checkTimer.Dispose();

            _tcpClient.Close();
            _tcpClient = null;          
            OnDisconnectedEvent();
        }

19 Source : TcpClient.cs
with MIT License
from dust63

protected virtual void Dispose(bool disposing)
        {
            if (_disposedValue)
                return;

            if (!disposing)
            {
                _readTimer.Dispose();
                _checkTimer.Dispose();
            }
            try
            {
                _tcpClient?.Close();
            }
            finally
            {
                _tcpClient = null;
                _disposedValue = true;
            }
        }

19 Source : TSocket.cs
with Apache License 2.0
from duyanming

public override void Open()
        {
            if (IsOpen)
            {
                throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
            }

            if (String.IsNullOrEmpty(Host))
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
            }

            if (Port <= 0)
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
            }

            if (TcpClient == null)
            {
                InitSocket();
            }

            if (timeout == 0)            // no timeout -> infinite
            {
                TcpClient.Connect(Host, Port);
            }
            else                        // we have a timeout -> use it
            {
                var hlp = new ConnectHelper(TcpClient);
                var asyncres = TcpClient.BeginConnect(Host, Port, new AsyncCallback(ConnectCallback), hlp);
                var bConnected = asyncres.AsyncWaitHandle.WaitOne(timeout) && TcpClient.Connected;
                if (!bConnected)
                {
                    lock (hlp.Mutex)
                    {
                        if (hlp.CallbackDone)
                        {
                            asyncres.AsyncWaitHandle.Close();
                            TcpClient.Close();
                        }
                        else
                        {
                            hlp.DoCleanup = true;
                            TcpClient = null;
                        }
                    }
                    throw new TTransportException(TTransportException.ExceptionType.TimedOut, "Connect timed out");
                }
            }

            inputStream = TcpClient.GetStream();
            outputStream = TcpClient.GetStream();
        }

19 Source : TSocket.cs
with Apache License 2.0
from duyanming

public override void Close()
        {
            base.Close();
            if (TcpClient != null)
            {
                TcpClient.Close();
                TcpClient = null;
            }
        }

19 Source : TTLSSocket.cs
with Apache License 2.0
from duyanming

public override void Open()
        {
            if (IsOpen)
            {
                throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
            }

            if (String.IsNullOrEmpty(Host))
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
            }

            if (Port <= 0)
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
            }

            if (TcpClient == null)
            {
                InitSocket();
            }

            if (timeout == 0)            // no timeout -> infinite
            {
                TcpClient.Connect(Host, Port);
            }
            else                        // we have a timeout -> use it
            {
                var hlp = new ConnectHelper(TcpClient);
                var asyncres = TcpClient.BeginConnect(Host, Port, new AsyncCallback(ConnectCallback), hlp);
                var bConnected = asyncres.AsyncWaitHandle.WaitOne(timeout) && TcpClient.Connected;
                if (!bConnected)
                {
                    lock (hlp.Mutex)
                    {
                        if (hlp.CallbackDone)
                        {
                            asyncres.AsyncWaitHandle.Close();
                            TcpClient.Close();
                        }
                        else
                        {
                            hlp.DoCleanup = true;
                            TcpClient = null;
                        }
                    }
                    throw new TTransportException(TTransportException.ExceptionType.TimedOut, "Connect timed out");
                }
            }

            setupTLS();
        }

19 Source : TTLSSocket.cs
with Apache License 2.0
from duyanming

public override void Close()
        {
            base.Close();
            if (TcpClient != null)
            {
                TcpClient.Close();
                TcpClient = null;
            }

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

19 Source : Hl7Mllp.cs
with GNU Lesser General Public License v2.1
from dvtk-org

public void Stop()
		{
            _normalShutdown = true;

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

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

			if (_tcpListener != null)
			{
				_tcpListener.Stop();
				_tcpListener = null;
			}
		}

19 Source : TcpClient.cs
with Apache License 2.0
from eaglet2006

public void Connect(int connectTimeout)
        {
            if (connectTimeout > 30000)
            {
                Connect();
                return;
            }

            if (_Client == null)
            {
                _Client = new System.Net.Sockets.TcpClient();
            }

            IPEndPoint serverEndPoint =
               new IPEndPoint(RemoteAddress, Port);

            IAsyncResult ar = _Client.BeginConnect(serverEndPoint.Address, 
                serverEndPoint.Port, null, null);
            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(connectTimeout, false))
                {
                    _Client.Close();
                    throw new TimeoutException(string.Format("Try to connect {0} timeout", serverEndPoint));
                }

                _Client.EndConnect(ar);
            }
            finally
            {
                wh.Close();
            } 

            _ClientStream = _Client.GetStream();

            if (_Async)
            {
                _Thread = new Thread(AsyncMessageRecv);
                _Thread.IsBackground = true;
                _Thread.Start();
            }
        }

19 Source : TcpClient.cs
with Apache License 2.0
from eaglet2006

public void Dispose()
        {
            try
            {
                if (_ClientStream != null)
                {
                    _ClientStream.Close();
                }

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

                if (_Async)
                {
                    if (_Thread != null)
                    {
                        if (!ThreadClosed)
                        {
                            _Thread.Abort();
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                _ClientStream = null;
                _Client = null;
                _Thread = null;
            }
        }

19 Source : TcpServer.cs
with Apache License 2.0
from eaglet2006

private void ListenForClients()
        {
            try
            {
                this._TcpListener.Start();

                while (true)
                {
                    //blocks until a client has connected to the server
                    System.Net.Sockets.TcpClient client = this._TcpListener.AcceptTcpClient();

                    try
                    {
                        //create a thread to handle communication
                        //with connected client
                        Thread clientThread =
                           new Thread(new
                           ParameterizedThreadStart(HandleClientComm));

                        clientThread.IsBackground = true;

                        PCB pcb = GetPCB(client);

                        if (pcb == null)
                        {
                            //Over max connect number
                            ReturnMessage(client, client, new MessageHead(), new Exception("Too many connects on server"), null);

                            System.Threading.Thread.Sleep(200);

                            client.Close();
                            throw new Exception("Too many connects on server");
                        }
                        else
                        {
                            clientThread.Start(pcb);
                        }
                    }
                    catch (Exception e)
                    {
                        OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
                    }
                }
            }
            catch (Exception e)
            {
                OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
            }
        }

19 Source : TcpServer.cs
with Apache License 2.0
from eaglet2006

private void HandleClientComm(object pcb)
        {
            PCB p = (PCB)pcb;

            System.Net.Sockets.TcpClient tcpClient = p.Client;
            object lockObj = new object();

            try
            {
                try
                {
                    OnConnectEstablishEvent(new ConnectEstablishEventArgs(p.ThreadId));
                }
                catch (Exception e)
                {
                    OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
                }

                System.Net.Sockets.NetworkStream clientStream = tcpClient.GetStream();

                TcpCacheStream tcpStream = new TcpCacheStream(clientStream);

                while (true)
                {
                    MessageHead msgHead = new MessageHead();

                    try
                    {
                        bool disconnected = false;
                        object msg = null;

                        //Recevie data
                        //Stream tcpStream = clientStream;

                        byte[] revBuf = new byte[4];
                        int offset = 0;

                        while (offset < 4)
                        {
                            int len;

                            try
                            {
                                len = tcpStream.Read(revBuf, offset, 4 - offset);
                            }
                            catch
                            {
                                disconnected = true;
                                break;
                            }

                            if (len == 0)
                            {
                                //Disconnect
                                disconnected = true;
                                break;
                            }

                            offset += len;
                        }

                        if (disconnected)
                        {
                            break;
                        }

                        msgHead.Event = BitConverter.ToInt16(revBuf, 0);
                        msgHead.Flag = (MessageFlag)BitConverter.ToInt16(revBuf, 2);

                        bool isAsync = (msgHead.Flag & MessageFlag.ASyncMessage) != 0;
                        int clreplacedId = -1;

                        if (isAsync)
                        {
                            if (!Hubble.Framework.IO.Stream.ReadToBuf(tcpStream, revBuf, 0, 4))
                            {
                                disconnected = true;
                                break;
                            }
                            else
                            {
                                clreplacedId = BitConverter.ToInt32(revBuf, 0);
                            }
                        }


                        if ((msgHead.Flag & MessageFlag.NullData) == 0)
                        {
                            if ((msgHead.Flag & MessageFlag.CustomSerialization) != 0)
                            {
                                if (RequireCustomSerialization != null)
                                {
                                    Hubble.Framework.Serialization.IMySerialization mySerializer =
                                        RequireCustomSerialization(msgHead.Event, null);

                                    if (mySerializer == null)
                                    {
                                        throw new Exception(string.Format("RequireCustomSerialization of Event = {0} is null!",
                                            msgHead.Event));
                                    }

                                    msg = mySerializer.Deserialize(tcpStream, mySerializer.Version);
                                }
                                else
                                {
                                    throw new Exception("RequireCustomSerialization of TcpClient is null!");
                                }
                            }
                            else if ((msgHead.Flag & MessageFlag.IsString) == 0)
                            {
                                IFormatter formatter = new BinaryFormatter();
                                msg = formatter.Deserialize(tcpStream);
                            }
                            else
                            {
                                if ((msgHead.Flag & MessageFlag.IsString) != 0 &&
                                    (msgHead.Flag & MessageFlag.ASyncMessage) != 0)
                                {
                                    MemoryStream m = new MemoryStream();

                                    byte b = (byte)tcpStream.ReadByte();
                                    while (b != 0)
                                    {
                                        m.WriteByte(b);
                                        b = (byte)tcpStream.ReadByte();
                                    }

                                    m.Position = 0;

                                    using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
                                    {
                                        msg = sr.ReadToEnd();
                                    }

                                }
                                else
                                {
                                    MemoryStream m = new MemoryStream();

                                    byte[] buf = new byte[1024];

                                    int len = 0;

                                    do
                                    {
                                        len = tcpStream.Read(buf, 0, buf.Length);
                                        if (buf[len - 1] == 0)
                                        {
                                            m.Write(buf, 0, len - 1);
                                            break;
                                        }
                                        else
                                        {
                                            m.Write(buf, 0, len);
                                        }
                                    } while (true);

                                    m.Position = 0;

                                    using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
                                    {
                                        msg = sr.ReadToEnd();
                                    }
                                }
                            }

                        }

                        MessageReceiveEventArgs receiveEvent = new MessageReceiveEventArgs(
                            this, msgHead, msg, p.ThreadId, clreplacedId, tcpClient, 
                            clientStream, lockObj);

                        Hubble.Framework.Serialization.IMySerialization customSerializer = null;

                        try
                        {
                            OnMessageReceiveEvent(receiveEvent);
                            customSerializer = receiveEvent.CustomSerializtion;
                        }
                        catch (System.Threading.ThreadAbortException)
                        {
                            receiveEvent.ReturnMsg = new System.Threading.ThreadInterruptedException("Thread abort. Maybe execute select too long. Please check the error log.");
                            System.Threading.Thread.ResetAbort();
                        }
                        catch (Exception e)
                        {
                            receiveEvent.ReturnMsg = e;
                        }

                        if (!isAsync)
                        {
                            ReturnMessage(lockObj, tcpClient, msgHead, receiveEvent.ReturnMsg, customSerializer);
                        }
                    }
                    catch (Exception innerException)
                    {
                        try
                        {
                            OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(msgHead, innerException));
                        }
                        catch
                        {
                        }

                        if (tcpClient.Connected)
                        {
                            tcpClient.Close();
                        }

                        throw innerException;
                    }
                }

                tcpClient.Close();
            }
            catch (Exception e)
            {
                OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
            }
            finally
            {
                try
                {
                    OnDisconnectEvent(new DisconnectEventArgs(p.ThreadId));
                }
                catch (Exception e)
                {
                    OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
                }

                RetPCB(p);
            }
        }

19 Source : FingerPrinting.cs
with GNU General Public License v3.0
from ElevenPaths

protected void TcpDisconnect()
        {
            tcp.Close();
        }

19 Source : FingerPrinting.cs
with GNU General Public License v3.0
from ElevenPaths

protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    tcp.Close();
                }

                disposedValue = true;
            }
        }

19 Source : Miner.cs
with GNU General Public License v3.0
from Elycin

private void SafeClose(TcpClient client)
        {
            try
            {
                if (client != null) if (client.Connected) client.Close();
            }
            catch (Exception e)
            {
                Program.ConsoleWriteLineWithColor(ConsoleColor.Red, "Failed to close TCP Socket: " + e.ToString());
            }
        }

19 Source : Client.cs
with MIT License
from EricBatlle

private void CloseClient()
	{
		ClientLog("Client Closed", Color.red);

		//Reset everything to defaults
		if (m_Client.Connected)
			m_Client.Close();

		if (m_Client != null)
			m_Client = null;

		OnClientClosed?.Invoke();
	}

19 Source : Server.cs
with MIT License
from EricBatlle

protected virtual void CloseServer()
	{
		ServerLog("Server Closed", Color.red);
		//Close client connection
		if (m_Client != null)
		{
			ServerLog("Remember to close Client!", Color.black);
			m_NetStream?.Close();
			m_NetStream = null;
			m_Client.Close();
			m_Client = null;
			OnClientDisconnected?.Invoke();
		}
		//Close server connection
		if (m_Server != null)
		{
			m_Server.Stop();
			m_Server = null;
		}

		if (m_ListenClientMsgsCoroutine != null)
		{
			StopCoroutine(m_ListenClientMsgsCoroutine);
			m_ListenClientMsgsCoroutine = null;
		}

		OnServerClosed?.Invoke();
	}

19 Source : Server.cs
with MIT License
from EricBatlle

protected virtual void CloseClientConnection()
	{
		ServerLog("Close Connection with Client", Color.red);
		//Reset everything to defaults
		if (m_ListenClientMsgsCoroutine != null)
		{
			StopCoroutine(m_ListenClientMsgsCoroutine);
			m_ListenClientMsgsCoroutine = null;
		}

		m_Client.Close();
		m_Client = null;

		OnClientDisconnected?.Invoke();

		//Waiting to Accept a new Client
		m_Server.BeginAcceptTcpClient(ClientConnected, null);
	}

19 Source : GhostNetRemoteConnection.cs
with MIT License
from EverestAPI

protected override void Dispose(bool disposing) {
            lock (DisposeLock) {
                if (Disposed)
                    return;
                Disposed = true;

                base.Dispose(disposing);

                ManagementReader?.Dispose();
                ManagementReader = null;

                ManagementStream?.Dispose();
                ManagementStream = null;

                ManagementClient?.Close();
                ManagementClient = null;

                UpdateClient?.Close();
                UpdateClient = null;
            }
        }

19 Source : ProxyClient.cs
with MIT License
from extremecodetv

public NetworkStream GetDestinationStream(string destinationHost, int destinationPort)
        {
            TcpClient tcpClient = null;
            client.Settings = Settings;

            #region Create Connection

            tcpClient = new TcpClient();
            Exception connectException = null;
            var connectDoneEvent = new ManualResetEventSlim();

            try
            {
                tcpClient.BeginConnect(Settings.Host, Settings.Port, new AsyncCallback(
                    (ar) =>
                    {
                        if (tcpClient.Client != null)
                        {
                            try
                            {
                                tcpClient.EndConnect(ar);
                            }
                            catch (Exception ex)
                            {
                                connectException = ex;
                            }

                            connectDoneEvent.Set();
                        }
                    }), tcpClient
                );
            }
            catch (Exception ex)
            {
                tcpClient.Close();

                if (ex is SocketException || ex is SecurityException)
                {
                    throw new ProxyException("Failed to connect to proxy-server", ex);
                }

                throw;
            }

            if (!connectDoneEvent.Wait(Settings.ConnectTimeout))
            {
                tcpClient.Close();
                throw new ProxyException("Failed to connect to proxy-server");
            }

            if (connectException != null)
            {
                tcpClient.Close();

                if (connectException is SocketException)
                {
                    throw new ProxyException("Failed to connect to proxy-server", connectException);
                }
                else
                {
                    throw connectException;
                }
            }

            if (!tcpClient.Connected)
            {
                tcpClient.Close();
                throw new ProxyException("Failed to connect to proxy-server");
            }

            #endregion

            tcpClient.SendTimeout = Settings.ReadWriteTimeOut;
            tcpClient.ReceiveTimeout = Settings.ReadWriteTimeOut;
            
            var connectedTcpClient = client.CreateConnection(
                destinationHost,
                destinationPort,
                tcpClient);

            return connectedTcpClient.GetStream();
        }

19 Source : Socks4.cs
with MIT License
from extremecodetv

public TcpClient CreateConnection(string destinationHost, int destinationPort, TcpClient client)
        {
            if (String.IsNullOrEmpty(destinationHost))
            {
                throw new ArgumentException(nameof(destinationHost));
            }

            if (!ExceptionHelper.ValidateTcpPort(destinationPort))
            {
                throw new ArgumentOutOfRangeException(nameof(destinationPort));
            }

            if (client == null || !client.Connected)
            {
                throw new SocketException();
            }

            try
            {
                SendCommand(client.GetStream(), CommandConnect, destinationHost, destinationPort);
            }
            catch (Exception ex)
            {
                client.Close();

                if (ex is IOException || ex is SocketException)
                {
                    throw new ProxyException("Error while working with proxy", ex);
                }

                throw;
            }

            return client;
        }

19 Source : Socks5.cs
with MIT License
from extremecodetv

public TcpClient CreateConnection(string destinationHost, int destinationPort, TcpClient client)
        {
            if (String.IsNullOrEmpty(destinationHost))
            {
                throw new ArgumentException(nameof(destinationHost));
            }

            if (!ExceptionHelper.ValidateTcpPort(destinationPort))
            {
                throw new ArgumentOutOfRangeException(nameof(destinationPort));
            }

            if (client == null || !client.Connected)
            {
                throw new SocketException();
            }

            try
            {
                NetworkStream nStream = client.GetStream();

                InitialNegotiation(nStream);
                SendCommand(nStream, CommandConnect, destinationHost, destinationPort);
            }
            catch (Exception ex)
            {
                client.Close();

                if (ex is IOException || ex is SocketException)
                {
                    throw new ProxyException("Error while working with proxy", ex);
                }

                throw;
            }

            return client;
        }

19 Source : TcpNetClient.cs
with GNU General Public License v3.0
from Extremelyd1

public void Disconnect() {
            if (!_tcpClient.Connected) {
                Logger.Get().Warn(this, "TCP client was not connected, trying to close anyway");
            }

            _tcpClient.Close();
        }

19 Source : Client.cs
with MIT License
from EZForever

void TaskMain()
        {
            // DO NOT call this inside of the Client constructor
            // At that time the instance is not recorded
            Gui.theInstance.InvokeOn((FMain Me) => Me.RefreshGuiTargets());

            try
            {
                while(true)
                {
                    byte[] buffer = ReceiveDirect();
                    if (buffer == null)
                        break;
                    OnRecv(buffer);
                }
            }
            catch(IOException e)
            {
                Logger.W(Program.GetResourceString("Threads.Client.Disconnected", clientName, e.Message));
            }
            finally
            {
                stream.Close();
                client.Close();

                Gui.theInstance.InvokeOn((FMain Me) => Me.RefreshGuiTargets());
            }
        }

19 Source : Client.cs
with MIT License
from EZForever

public byte[] Expect(Puppet.PACKET_TYPE type, bool direct = false)
        {
            direct = direct || rxForceDirect;

            byte[] buffer = direct ? ReceiveDirect() : Receive();
            if (buffer == null)
                return null;

            if (Puppet.Util.Deserialize<Puppet.PACKET>(buffer).type != type)
            {
                if(direct)
                {
                    // IOException can be handled by .ctor() / TaskMain()
                    throw new IOException(Program.GetResourceString("Threads.Client.MalformedPacket"));
                }
                else
                {
                    // Kill client, and return an error for command execution
                    stream.Close();
                    client.Close();
                    throw new ArgumentException(Program.GetResourceString("Threads.Client.MalformedPacket"));
                }
            }
            return buffer;
        }

See More Examples