System.Net.Sockets.TcpClient.GetStream()

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

805 Examples 7

19 Source : CelesteNetTCPUDPConnection.cs
with MIT License
from 0x0ade

private void InitTCPUDP(TcpClient tcp, UdpClient? udp) {
            TCP = tcp;
            TCPReaderStream = new(new BufferedStream(tcp.GetStream()));
            TCPWriterStream = new(new BufferedStream(tcp.GetStream()));
            TCPReader = new(Data, DefaultSendQueue.Strings, TCPReaderStream, true);
            TCPWriter = new(TCPWriterStream, CelesteNetUtils.UTF8NoBOM, true);

            UDP = udp;
        }

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

public void Connect(string host, int port)
        {
            // TcpClient
            tcpClient = new TcpClient();
            tcpClient.SendTimeout = Options.SocketTimeout;
            tcpClient.ReceiveTimeout = Options.SocketTimeout;
            tcpClient.Connect(IPAddress.Parse(host), port);

            // NetworkStream
            networkStream = tcpClient.GetStream();
            networkStream.WriteTimeout = Options.SocketTimeout;
            networkStream.ReadTimeout = Options.SocketTimeout;
        }

19 Source : Program.cs
with MIT License
from abanu-org

[MethodImpl(MethodImplOptions.Synchronized)]
        private static void Start()
        {
            while (true)
            {
                try
                {
                    stream?.Dispose();
                }
                catch
                {
                }
                try
                {
                    client?.Dispose();
                }
                catch
                {
                }
                try
                {
                    thRead?.Abort();
                }
                catch
                {
                }
                try
                {
                    thWrite?.Abort();
                }
                catch
                {
                }
                thRead = null;
                thWrite = null;

                ms.SetLength(0);
                WriteQueue.Clear();

                try
                {
                    client = new TcpClient();
                    Console.WriteLine("Connecting...");
                    client.Connect("localhost", 2244);
                    Console.WriteLine("Connected");
                    receiveBufSize = client.ReceiveBufferSize;
                    stream = client.GetStream();

                    thRead = new Thread(ReadThread);
                    thRead.Start();

                    thWrite = new Thread(WriteThread);
                    thWrite.Start();

                    IsConnecting = false;

                    break;
                }
                catch (SocketException ex)
                {
                    Console.WriteLine(ex);
                    Thread.Sleep(3000);
                }
            }
        }

19 Source : OVRNetwork.cs
with MIT License
from absurd-joy

public void Disconnect()
		{
			if (tcpClient != null)
			{
				if (!readyReceiveDataEvent.WaitOne(5))
				{
					Debug.LogWarning("[OVRNetworkTcpClient] readyReceiveDataEvent not signaled. data receiving timeout?");
				}

				Debug.Log("[OVRNetworkTcpClient] close tcpClient");
				try
				{
					tcpClient.GetStream().Close();
					tcpClient.Close();
				}
				catch (Exception e)
				{
					Debug.LogWarning("[OVRNetworkTcpClient] " + e.Message);
				}
				tcpClient = null;

				if (connectionStateChangedCallback != null)
				{
					connectionStateChangedCallback();
				}
			}
			else
			{
				Debug.LogWarning("[OVRNetworkTcpClient] not connected");
			}
		}

19 Source : OVRNetwork.cs
with MIT License
from absurd-joy

public void Broadcast(int payloadType, byte[] payload)
		{
			if (payload.Length > OVRNetwork.MaxPayloadLength)
			{
				Debug.LogWarningFormat("[OVRNetworkTcpServer] drop payload because it's too long: {0} bytes", payload.Length);
			}

			FrameHeader header = new FrameHeader();
			header.protocolIdentifier = FrameHeaderMagicIdentifier;
			header.payloadType = payloadType;
			header.payloadLength = payload.Length;

			byte[] headerBuffer = header.ToBytes();

			byte[] dataBuffer = new byte[headerBuffer.Length + payload.Length];
			headerBuffer.CopyTo(dataBuffer, 0);
			payload.CopyTo(dataBuffer, headerBuffer.Length);

			lock (clientsLock)
			{
				foreach (TcpClient client in clients)
				{
					if (client.Connected)
					{
						try
						{
							client.GetStream().BeginWrite(dataBuffer, 0, dataBuffer.Length, new AsyncCallback(DoWriteDataCallback), client.GetStream());
						}
						catch (SocketException e)
						{
							Debug.LogWarningFormat("[OVRNetworkTcpServer] close client because of socket error: {0}", e.Message);
							client.GetStream().Close();
							client.Close();
						}
					}
				}
			}
		}

19 Source : OVRNetwork.cs
with MIT License
from absurd-joy

public void Tick()
		{
			if (tcpClient == null || !tcpClient.Connected)
			{
				return;
			}

			if (readyReceiveDataEvent.WaitOne(TimeSpan.Zero))
			{
				if (tcpClient.GetStream().DataAvailable)
				{
					if (receivedBufferDataSize >= OVRNetwork.MaxBufferLength)
					{
						Debug.LogWarning("[OVRNetworkTcpClient] receive buffer overflow. It should not happen since we have the constraint on message size");
						Disconnect();
						return;
					}

					readyReceiveDataEvent.Reset();
					int maximumDataSize = OVRSystemPerfMetrics.MaxBufferLength - receivedBufferDataSize;

					tcpClient.GetStream().BeginRead(receivedBuffers[receivedBufferIndex], receivedBufferDataSize, maximumDataSize, new AsyncCallback(OnReadDataCallback), tcpClient.GetStream());
				}
			}
		}

19 Source : HotReloadConnectedClient.cs
with MIT License
from adospace

public async void Run(CancellationToken cancellationToken)
        {
            var stream = _connectedClient.GetStream();
            var factory = new WebSocketServerFactory();

            try
            {
                var context = await factory.ReadHttpHeaderFromStreamAsync(stream, cancellationToken);

                if (!context.IsWebSocketRequest)
                {
                    _connectedClient.Close();
                    return;
                }

                var webSocket = await factory.AcceptWebSocketAsync(context, cancellationToken);

                await Receive(webSocket, cancellationToken);
            }
            catch (OperationCanceledException)
            { 
            
            }
        }

19 Source : HotReloadCommand.cs
with MIT License
from adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(ProgressMonitor progressMonitor, string replacedemblyPath, bool debugging)
        {
            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                await progressMonitor.Log.WriteLineAsync($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator");
            }
            catch (Exception ex)
            {
                await progressMonitor.ErrorLog.WriteLineAsync($@"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}");

                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 Source : HotReloadConnectedClient.cs
with MIT License
from adospace

public void Run(CancellationToken cancellationToken)
        {
            var stream = _connectedClient.GetStream();
            var binaryReader = new BinaryReader(stream);
            var binaryWriter = new BinaryWriter(stream);
            try
            {
                int length = binaryReader.ReadInt32();
                if (length == -1)
                    return;

                var replacedemblyRaw = binaryReader.ReadBytes(length);
                byte[] replacedemblySymbolStoreRaw = null;

                length = binaryReader.ReadInt32();
                if (length > 0)
                {
                    replacedemblySymbolStoreRaw = binaryReader.ReadBytes(length);
                }

                _server.OnReceivedreplacedembly(replacedemblyRaw, replacedemblySymbolStoreRaw);

                binaryWriter.Write(true);

                binaryWriter.Flush();
            }
            catch (OperationCanceledException)
            {

            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex);
            }
        }

19 Source : Program.cs
with MIT License
from adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, bool debugging = true)
        {
            
            //ThreadHelper.ThrowIfNotOnUIThread();

            //outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
            //outputPane.Activate(); // Brings this pane into view

            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
               
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                Console.WriteLine($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($@"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 Source : ReloadCommand.cs
with MIT License
from adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, IVsOutputWindowPane outputPane, bool debugging)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            //ThreadHelper.ThrowIfNotOnUIThread();

            //outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
            //outputPane.Activate(); // Brings this pane into view

            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
                
                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                outputPane.OutputStringThreadSafe($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                outputPane.OutputStringThreadSafe($@"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 Source : TcpSocket.cs
with Apache License 2.0
from advancer68

public void Connect(string host, int port)
    {
        client = new TcpClient();
        client.Connect(host, port);
        tcpStream = client.GetStream();
        BeginRead();
    }

19 Source : PeerDialer.cs
with MIT License
from AElfProject

private async Task<X509Certificate> RetrieveServerCertificateAsync(DnsEndPoint remoteEndpoint)
        {
            Logger.LogDebug($"Starting certificate retrieval for {remoteEndpoint}.");

            TcpClient client = null;

            try
            {
                client = new TcpClient();
                using (var cts = new CancellationTokenSource())
                {
                    cts.CancelAfter(NetworkConstants.DefaultSslCertifFetchTimeout);
                    await client.ConnectAsync(remoteEndpoint.Host, remoteEndpoint.Port).WithCancellation(cts.Token);

                    using (var sslStream = new SslStream(client.GetStream(), true, (a, b, c, d) => true))
                    {
                        sslStream.ReadTimeout = NetworkConstants.DefaultSslCertifFetchTimeout;
                        sslStream.WriteTimeout = NetworkConstants.DefaultSslCertifFetchTimeout;
                        await sslStream.AuthenticateAsClientAsync(remoteEndpoint.Host).WithCancellation(cts.Token);

                        if (sslStream.RemoteCertificate == null)
                        {
                            Logger.LogDebug($"Certificate from {remoteEndpoint} is null");
                            return null;
                        }

                        Logger.LogDebug($"Retrieved certificate for {remoteEndpoint}.");

                        return FromX509Certificate(sslStream.RemoteCertificate);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Logger.LogDebug($"Certificate retrieval connection timeout for {remoteEndpoint}.");
                return null;
            }
            catch (Exception ex)
            {
                // swallow exception because it's currently not a hard requirement to 
                // upgrade the connection.
                Logger.LogWarning(ex, $"Could not retrieve certificate from {remoteEndpoint}.");
            }
            finally
            {
                client?.Close();
            }

            return null;
        }

19 Source : GuiderImpl.cs
with MIT License
from agalasso

public bool Connect(string hostname, ushort port)
        {
            try
            {
                tcpCli = new TcpClient(hostname, port);
                sw = new StreamWriter(tcpCli.GetStream());
                sw.AutoFlush = true;
                sw.NewLine = "\r\n";
                sr = new StreamReader(tcpCli.GetStream());
                return true;
            }
            catch (Exception)
            {
                Close();
                return false;
            }
        }

19 Source : PaceClient.cs
with MIT License
from afxw

public byte[] ReadData()
        {
            var stream = TcpClient.GetStream();

            byte[] packetLengthBytes = new byte[4];

            int headerBytesRead = 0;
            int headerRead = 0;

            while (headerBytesRead < packetLengthBytes.Length)
            {
                headerRead = stream.Read(packetLengthBytes, headerBytesRead, packetLengthBytes.Length);
                headerBytesRead += headerRead;
            }

            int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            byte[] packetData = new byte[packetLength];

            int bytesRead = 0;
            int read = 0;

            while (bytesRead < packetLength)
            {
                read = stream.Read(packetData, bytesRead, packetLength - bytesRead);
                bytesRead += read;
            }

            return packetData;
        }

19 Source : PaceClient.cs
with MIT License
from afxw

public void SendData(byte[] data)
        {
            TcpClient.GetStream().Write(BitConverter.GetBytes(data.Length), 0, 4);
            TcpClient.GetStream().Write(data, 0, data.Length);
        }

19 Source : TCPClientManager.cs
with MIT License
from akihiro0105

private void ConnectCallback(IAsyncResult ar)
        {
            var tcp = (TcpClient)ar.AsyncState;
            tcp.EndConnect(ar);
            tcp.ReceiveTimeout = 100;
            stream = tcp.GetStream();
            var bytes = new byte[tcp.ReceiveBufferSize];
            while (isActiveThread)
            {
                try
                {
                    var num = stream.Read(bytes, 0, bytes.Length);
                    if (num > 0)
                    {
                        var data = new byte[num];
                        Array.Copy(bytes, 0, data, 0, num);
                        if (ListenerMessageEvent != null) ListenerMessageEvent(Encoding.UTF8.GetString(data));
                        if (ListenerByteEvent != null) ListenerByteEvent(data);
                    }
                }
                catch (Exception e)
                {
                    Console.Write(e);
                }
            }
            stream.Close();
            stream = null;
            tcp.Close();
        }

19 Source : TCPServerManager.cs
with MIT License
from akihiro0105

private void AcceptTcpClient(IAsyncResult ar)
        {
            var listener = (TcpListener)ar.AsyncState;

            var tcpClient = listener.EndAcceptTcpClient(ar);
            listener.BeginAcceptTcpClient(AcceptTcpClient, listener);
            tcpClient.ReceiveTimeout = 100;
            var stream = tcpClient.GetStream();
            streamList.Add(stream);
            var bytes = new byte[tcpClient.ReceiveBufferSize];

            while (isActiveThread)
            {
                try
                {
                    var num = stream.Read(bytes, 0, bytes.Length);
                    if (num > 0)
                    {
                        for (int i = 0; i < streamList.Count; i++)
                        {
                            if (streamList[i].CanWrite == true) streamList[i].Write(bytes, 0, num);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.Write(e);
                }
                if (tcpClient.Client.Poll(1000, SelectMode.SelectRead) && tcpClient.Client.Available == 0) break;
            }
            stream.Close();
            tcpClient.Close();
        }

19 Source : Session.cs
with GNU General Public License v3.0
from AlanMorel

public void Init([NotNull] TcpClient client)
    {
        if (Disposed)
        {
            throw new ObjectDisposedException("Session has been disposed.");
        }

        // Allow client to close immediately
        client.LingerState = new(true, 0);
        Name = client.Client.RemoteEndPoint?.ToString();

        byte[] sivBytes = new byte[4];
        byte[] rivBytes = new byte[4];
        rng.GetBytes(sivBytes);
        rng.GetBytes(rivBytes);
        Siv = BitConverter.ToUInt32(sivBytes);
        Riv = BitConverter.ToUInt32(rivBytes);

        Client = client;
        NetworkStream = client.GetStream();
        SendCipher = new(VERSION, Siv, BLOCK_IV);
        RecvCipher = new(VERSION, Riv, BLOCK_IV);
    }

19 Source : EmulatorClientSocket.cs
with MIT License
from alanplotko

private void ProcessConnection(TcpClient tcpClient) {
      byte[] buffer = new byte[4];
      NetworkStream stream = tcpClient.GetStream();
      stream.ReadTimeout = kSocketReadTimeoutMillis;
      tcpClient.ReceiveTimeout = kSocketReadTimeoutMillis;
      while (!shouldStop) {
        int bytesRead = blockingRead(stream, buffer, 0, 4);
        if (bytesRead < 4) {
          // Caught by phoneEventSocketLoop.
          throw new Exception(
            "Failed to read from controller emulator app event socket." +
            "\nVerify that the controller emulator app is running.");
        }
        int msgLen = unpack32bits(correctEndianness(buffer), 0);

        byte[] dataBuffer = new byte[msgLen];
        bytesRead = blockingRead(stream, dataBuffer, 0, msgLen);
        if (bytesRead < msgLen) {
          // Caught by phoneEventSocketLoop.
          throw new Exception(
            "Failed to read from controller emulator app event socket." +
            "\nVerify that the controller emulator app is running.");
        }

        PhoneEvent proto =
            PhoneEvent.CreateBuilder().MergeFrom(dataBuffer).Build();
        phoneRemote.OnPhoneEvent(proto);

        if (!lastConnectionAttemptWreplaceduccessful) {
          Debug.Log("Successfully connected to controller emulator app.");
          // Log first failure after above successful read from event socket.
          lastConnectionAttemptWreplaceduccessful = true;
        }
      }
    }

19 Source : NamedClientStream.cs
with MIT License
from alchemz

void Connect(String server, int port, String message)
    {
        try
        {
            // Create a TcpClient.
            // Note, for this client to work you need to have a TcpServer 
            // connected to the same address as specified by the server, port
            // combination.
            TcpClient client = new TcpClient(server, port);

            // Translate the preplaceded message into ASCII and store it as a Byte array.
            Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

            // Get a client stream for reading and writing.
            //  Stream stream = client.GetStream();

            NetworkStream stream = client.GetStream();

            // Send the message to the connected TcpServer. 
            stream.Write(data, 0, data.Length);

            Console.WriteLine("Sent: {0}", message);

            // Receive the TcpServer.response.

            // Buffer to store the response bytes.
            data = new Byte[256];

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            Console.WriteLine("Received: {0}", responseData);

            // Close everything.
            stream.Close();
            client.Close();
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException: {0}", e);
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }

        Console.WriteLine("\n Press Enter to continue...");
        Console.Read();
    }

19 Source : NamedServerStream.cs
with MIT License
from alchemz

public void ListenForMessages(int port)
    {
        TcpListener server = null;
        try
        {
            // Set the TcpListener on port 13000.
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                Debug.Log("Waiting for a connection... ");

                // Perform a blocking call to accept requests.
                // You could also user server.AcceptSocket() here.
                using (TcpClient client = server.AcceptTcpClient())
                {

                    Debug.Log("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Debug.Log(String.Format("Received: {0}", data));

                        var viewModel = JsonUtility.FromJson<DataPointViewModel>(data);
                        lock (queueLock)
                        {
                            dataPointsQueue.Enqueue(viewModel);
                        }

                        // Process the data sent by the client.
                        data = data.ToUpper();

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        stream.Write(msg, 0, msg.Length);
                        Debug.Log(String.Format("Sent: {0}", data));
                    }
                }
            }
        }
        catch (SocketException e)
        {
            Debug.LogError(String.Format("SocketException: {0}", e));
        }
        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }
    }

19 Source : DV_Client.cs
with MIT License
from alchemz

private async Task ConnectAsync(String server, int port, String message)
        {
            try
            {
                // Create a TcpClient.
                // Note, for this client to work you need to have a TcpServer 
                // connected to the same address as specified by the server, port
                // combination.
                using (TcpClient client = new TcpClient())
                {
                    await client.ConnectAsync(server, port);

                    // Translate the preplaceded message into ASCII and store it as a Byte array.
                    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

                    // Get a client stream for reading and writing.
                    //  Stream stream = client.GetStream();

                    using (NetworkStream stream = client.GetStream())
                    {

                        // Send the message to the connected TcpServer. 
                        stream.Write(data, 0, data.Length);

                        Console.WriteLine("Sent: {0}", message);

                        // Receive the TcpServer.response.

                        // Buffer to store the response bytes.
                        data = new Byte[256];

                        // String to store the response ASCII representation.
                        String responseData = String.Empty;

                        // Read the first batch of the TcpServer response bytes.
                        Int32 bytes = stream.Read(data, 0, data.Length);
                        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                        Console.WriteLine("Received: {0}", responseData);
                    }
                }
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }

            Console.WriteLine("\n Press Enter to continue...");
            Console.Read();
        }

19 Source : TCPServerEnd.cs
with MIT License
from alchemz

public void ListenForMessage(int port)
	    {
	        TcpListener server = null;
	        try
	        {
	            // Set the TcpListener on port 13000.
	           
	            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

	            // TcpListener server = new TcpListener(port);
	            server = new TcpListener(localAddr, port);

	            // Start listening for client requests.
	            server.Start();

	            // Buffer for reading data
	            Byte[] bytes = new Byte[256];
	            String data = null;

	            // Enter the listening loop.
	            while (true)
	            {
				Debug.Log("Waiting for a connection... ");
	                //Console.Write("Waiting for a connection... ");

	                // Perform a blocking call to accept requests.
	                // You could also user server.AcceptSocket() here.
	                TcpClient client = server.AcceptTcpClient();
				Debug.Log("Connected!");

	                data = null;

	                // Get a stream object for reading and writing
	                NetworkStream stream = client.GetStream();

	                int i;

	                // Loop to receive all the data sent by the client.
	                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
	                {
	                    // Translate data bytes to a ASCII string.
	                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
					Debug.Log(String.Format("Received: {0}", data));

	                    // Process the data sent by the client.
	                    data = data.ToUpper();

	                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

	                    // Send back a response.
	                    stream.Write(msg, 0, msg.Length);
					Debug.Log(String.Format("Sent: {0}", data));
	                }

	                // Shutdown and end connection
	                client.Close();
	            }
	        }
	        catch (SocketException e)
	        {
			Debug.LogError(String.Format("SocketException: {0}", e));
	        }
	        finally
	        {
	            // Stop listening for new clients.
	            server.Stop();
	        }
			        
	    }

19 Source : TCPServerEnd.cs
with MIT License
from alchemz

public void ListenForMessages(int port)
	    {
	        TcpListener server = null;
	        try
	        {
	            // Set the TcpListener on port 13000.
	           
	            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

	            // TcpListener server = new TcpListener(port);
	            server = new TcpListener(localAddr, port);

	            // Start listening for client requests.
	            server.Start();

	            // Buffer for reading data
	            Byte[] bytes = new Byte[256];
	            String data = null;

	            // Enter the listening loop.
	            while (true)
	            {
				Debug.Log("Waiting for a connection... ");
	                //Console.Write("Waiting for a connection... ");

	                // Perform a blocking call to accept requests.
	                // You could also user server.AcceptSocket() here.
	                TcpClient client = server.AcceptTcpClient();
				Debug.Log("Connected!");

	                data = null;

	                // Get a stream object for reading and writing
	                NetworkStream stream = client.GetStream();

	                int i;

	                // Loop to receive all the data sent by the client.
	                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
	                {
	                    // Translate data bytes to a ASCII string.
	                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
					Debug.Log(String.Format("Received: {0}", data));

//					var viewModel=new DataPointViewModel();
//					viewModel.rightAscendsion = UnityEngine.Random.value;
//					viewModel.declination= UnityEngine.Random.Range(-1f,1f);
//					viewModel.color= Color.cyan;
					var viewModel=JsonUtility.FromJson<DataPointViewModel>(data);
					lock(queueLock)
					{
					dataPointsQueue.Enqueue(viewModel);
					}

	                    // Process the data sent by the client.

	                    data = data.ToUpper();

	                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

	                    // Send back a response.
	                    stream.Write(msg, 0, msg.Length);
					Debug.Log(String.Format("Sent: {0}", data));
	                }

	                // Shutdown and end connection
	                client.Close();
	            }
	        }
	        catch (SocketException e)
	        {
			Debug.LogError(String.Format("SocketException: {0}", e));
	        }
	        finally
	        {
	            // Stop listening for new clients.
	            server.Stop();
	        }
			        
	    }

19 Source : Context.cs
with MIT License
from alexanderdna

private async Task readAsync()
        {
            // How it works:
            // Messages are serialized as strings delimited by '\n' character.
            // They are read from the network stream and sometimes we can't
            // just read one whole message string in one ReadAsync call.
            // So we will add read characters to a string builder and call it
            // a complete message when encountering a '\n' character. Then
            // we clear the builder and add what would be the beginning of the
            // next message.

            if (ShouldDisconnect is false && Client.Available > 0)
            {
                var stream = Client.GetStream();

                int nRead = await stream.ReadAsync(inBuffer.AsMemory(0, inBuffer.Length));
                if (nRead == 0) return;

                // replaceduming messages consist of only ASCII characters.
                // This will speed up reading because Encoding.UTF8.GetString is not used.
                for (int i = 0; i < nRead; ++i)
                {
                    inBufferreplacedtring[i] = (char)(inBuffer[i] & 0x7f);
                }

                // Read characters may consist of: part of 1 message, 1 message or many messages.
                
                int pos, posNewLine = 0;
                do
                {
                    pos = -1;
                    for (int i = posNewLine; i < nRead; ++i)
                    {
                        if (inBufferreplacedtring[i] == '\n')
                        {
                            pos = i;
                            break;
                        }
                    }

                    if (pos >= 0)
                    {
                        // Delimiter found. Try to complete the latest message and clear sb.

                        sb.Append(inBufferreplacedtring, posNewLine, pos - posNewLine);

                        // Message is too long. Disconnect the peer now because we don't want any troubles.
                        if (sb.Length > MaxMessageLength)
                        {
                            sb.Clear();
                            ShouldDisconnect = true;
                            break;
                        }

                        posNewLine = pos + 1;

                        var msgJson = sb.ToString();
                        try
                        {
                            var msg = Message.Deserialize(msgJson);
                            inMessageQueue.Enqueue(msg);
                        }
                        catch (Newtonsoft.Json.JsonException)
                        {
                            ShouldDisconnect = true;
                        }

                        sb.Length = 0;
                    }
                    else
                    {
                        // Delimiter not found. Add what we have read to sb and wait for more data to be received.

                        sb.Append(inBufferreplacedtring, posNewLine, nRead - posNewLine);

                        // Message is too long. Disconnect the peer now because we don't want any troubles.
                        if (sb.Length > MaxMessageLength)
                        {
                            sb.Clear();
                            ShouldDisconnect = true;
                            break;
                        }
                    }
                } while (pos >= 0 && pos < nRead);
            }
        }

19 Source : Context.cs
with MIT License
from alexanderdna

public void Close()
        {
            try
            {
                Client.GetStream().Close();
                Client.Close();
            }
            catch (ObjectDisposedException)
            {
            }
        }

19 Source : Context.cs
with MIT License
from alexanderdna

private async Task writeAsync(Message msg)
        {
            var msgJson = Message.Serialize(msg);
            var stream = Client.GetStream();
            int pos = 0, nRemaining = msgJson.Length;
            while (nRemaining > 0 && ShouldDisconnect is false)
            {
                int bytesToCopy = Math.Min(outBuffer.Length, msgJson.Length - pos);
                for (int i = pos, j = 0, c = pos + bytesToCopy; i < c; ++i, ++j)
                {
                    outBuffer[j] = (byte)(msgJson[i] & 0x7f);
                }
                nRemaining -= bytesToCopy;
                pos += bytesToCopy;

                await stream.WriteAsync(outBuffer.AsMemory(0, bytesToCopy));
            }

            stream.WriteByte((byte)'\n');
            await stream.FlushAsync();
        }

19 Source : DnsClientBase.cs
with Apache License 2.0
from alexreinert

private byte[] QueryByTcp(IPAddress nameServer, byte[] messageData, int messageLength, ref TcpClient tcpClient, ref NetworkStream tcpStream, out IPAddress responderAddress)
		{
			responderAddress = nameServer;

			if (!IsTcpEnabled)
				return null;

			IPEndPoint endPoint = new IPEndPoint(nameServer, _port);

			try
			{
				if (tcpClient == null)
				{
					tcpClient = new TcpClient(nameServer.AddressFamily)
					{
						ReceiveTimeout = QueryTimeout,
						SendTimeout = QueryTimeout
					};

					if (!tcpClient.TryConnect(endPoint, QueryTimeout))
						return null;

					tcpStream = tcpClient.GetStream();
				}

				int tmp = 0;
				byte[] lengthBuffer = new byte[2];

				if (messageLength > 0)
				{
					DnsMessageBase.EncodeUShort(lengthBuffer, ref tmp, (ushort) messageLength);

					tcpStream.Write(lengthBuffer, 0, 2);
					tcpStream.Write(messageData, 0, messageLength);
				}

				if (!TryRead(tcpClient, tcpStream, lengthBuffer, 2))
					return null;

				tmp = 0;
				int length = DnsMessageBase.ParseUShort(lengthBuffer, ref tmp);

				byte[] resultData = new byte[length];

				return TryRead(tcpClient, tcpStream, resultData, length) ? resultData : null;
			}
			catch (Exception e)
			{
				Trace.TraceError("Error on dns query: " + e);
				return null;
			}
		}

19 Source : DnsClientBase.cs
with Apache License 2.0
from alexreinert

private async Task<QueryResponse> QueryByTcpAsync(IPAddress nameServer, byte[] messageData, int messageLength, TcpClient tcpClient, NetworkStream tcpStream, CancellationToken token)
		{
			if (!IsTcpEnabled)
				return null;

			try
			{
				if (tcpClient == null)
				{
					tcpClient = new TcpClient(nameServer.AddressFamily)
					{
						ReceiveTimeout = QueryTimeout,
						SendTimeout = QueryTimeout
					};

					if (!await tcpClient.TryConnectAsync(nameServer, _port, QueryTimeout, token))
					{
						return null;
					}

					tcpStream = tcpClient.GetStream();
				}

				int tmp = 0;
				byte[] lengthBuffer = new byte[2];

				if (messageLength > 0)
				{
					DnsMessageBase.EncodeUShort(lengthBuffer, ref tmp, (ushort) messageLength);

					await tcpStream.WriteAsync(lengthBuffer, 0, 2, token);
					await tcpStream.WriteAsync(messageData, 0, messageLength, token);
				}

				if (!await TryReadAsync(tcpClient, tcpStream, lengthBuffer, 2, token))
					return null;

				tmp = 0;
				int length = DnsMessageBase.ParseUShort(lengthBuffer, ref tmp);

				byte[] resultData = new byte[length];

				return await TryReadAsync(tcpClient, tcpStream, resultData, length, token) ? new QueryResponse(resultData, nameServer, tcpClient, tcpStream) : null;
			}
			catch (Exception e)
			{
				Trace.TraceError("Error on dns query: " + e);
				return null;
			}
		}

19 Source : DnsServer.cs
with Apache License 2.0
from alexreinert

private async void HandleTcpListenerAsync()
		{
			TcpClient client = null;

			try
			{
				try
				{
					client = await _tcpListener.AcceptTcpClientAsync();

					ClientConnectedEventArgs clientConnectedEventArgs = new ClientConnectedEventArgs(ProtocolType.Tcp, (IPEndPoint) client.Client.RemoteEndPoint);
					await ClientConnected.RaiseAsync(this, clientConnectedEventArgs);

					if (clientConnectedEventArgs.RefuseConnect)
						return;
				}
				finally
				{
					lock (_listenerLock)
					{
						_hasActiveTcpListener = false;
					}
				}

				StartTcpListenerTask();

				using (NetworkStream stream = client.GetStream())
				{
					while (true)
					{
						byte[] buffer = await ReadIntoBufferAsync(client, stream, 2);
						if (buffer == null) // client disconneted while reading or timeout
							break;

						int offset = 0;
						int length = DnsMessageBase.ParseUShort(buffer, ref offset);

						buffer = await ReadIntoBufferAsync(client, stream, length);
						if (buffer == null) // client disconneted while reading or timeout
						{
							throw new Exception("Client disconnted or timed out while sending data");
						}

						DnsMessageBase query;
						byte[] tsigMac;
						try
						{
							query = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null);
							tsigMac = query.TSigOptions?.Mac;
						}
						catch (Exception e)
						{
							throw new Exception("Error parsing dns query", e);
						}

						DnsMessageBase response;
						try
						{
							response = await ProcessMessageAsync(query, ProtocolType.Tcp, (IPEndPoint) client.Client.RemoteEndPoint);
						}
						catch (Exception ex)
						{
							OnExceptionThrownAsync(ex);

							response = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null);
							response.IsQuery = false;
							response.AdditionalRecords.Clear();
							response.AuthorityRecords.Clear();
							response.ReturnCode = ReturnCode.ServerFailure;
						}

						byte[] newTsigMac;

						length = response.Encode(true, tsigMac, false, out buffer, out newTsigMac);

						if (length <= 65535)
						{
							await stream.WriteAsync(buffer, 0, length);
						}
						else
						{
							if ((response.Questions.Count == 0) || (response.Questions[0].RecordType != RecordType.Axfr))
							{
								OnExceptionThrownAsync(new ArgumentException("The length of the serialized response is greater than 65,535 bytes"));

								response = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null);
								response.IsQuery = false;
								response.AdditionalRecords.Clear();
								response.AuthorityRecords.Clear();
								response.ReturnCode = ReturnCode.ServerFailure;

								length = response.Encode(true, tsigMac, false, out buffer, out newTsigMac);
								await stream.WriteAsync(buffer, 0, length);
							}
							else
							{
								bool isSubSequentResponse = false;

								while (true)
								{
									List<DnsRecordBase> nextPacketRecords = new List<DnsRecordBase>();

									while (length > 65535)
									{
										int lastIndex = Math.Min(500, response.AnswerRecords.Count / 2);
										int removeCount = response.AnswerRecords.Count - lastIndex;

										nextPacketRecords.InsertRange(0, response.AnswerRecords.GetRange(lastIndex, removeCount));
										response.AnswerRecords.RemoveRange(lastIndex, removeCount);

										length = response.Encode(true, tsigMac, isSubSequentResponse, out buffer, out newTsigMac);
									}

									await stream.WriteAsync(buffer, 0, length);

									if (nextPacketRecords.Count == 0)
										break;

									isSubSequentResponse = true;
									tsigMac = newTsigMac;
									response.AnswerRecords = nextPacketRecords;
									length = response.Encode(true, tsigMac, true, out buffer, out newTsigMac);
								}
							}
						}

						// Since support for multiple tsig signed messages is not finished, just close connection after response to first signed query
						if (newTsigMac != null)
							break;
					}
				}
			}
			catch (Exception ex)
			{
				OnExceptionThrownAsync(ex);
			}
			finally
			{
				try
				{
					// ReSharper disable once ConstantConditionalAccessQualifier
					client?.Close();
				}
				catch
				{
					// ignored
				}

				lock (_listenerLock)
				{
					_availableTcpListener++;
				}
				StartTcpListenerTask();
			}
		}

19 Source : TcpServer.cs
with MIT License
from alexwahl

private async Task ListenForClientConnection(CancellationToken ct)
        {
            this.tcpListener.Start();
            ct.Register(CancelComm);

            while (!ct.IsCancellationRequested)
            {
                //blocks until a client has connected to the server
                TcpClient client = await this.tcpListener.AcceptTcpClientAsync();

                //only one client can connect !
                NetworkStream clientStream = client.GetStream();
                
                Connection_established();

                
                byte[] message = new byte[4096];
                int bytesRead;

                while (!ct.IsCancellationRequested)
                {
                    try
                    {
                        bytesRead = 0;
                        //read message from client
                        bytesRead = await clientStream.ReadAsync(message, 0, 4096, ct).ConfigureAwait(true);
                        var str = System.Text.Encoding.Default.GetString(message, 0,bytesRead);
                        var answer = rigctrl.ExecCommand(str);
                        var answerBytes = (new System.Text.ASCIIEncoding()).GetBytes(answer);
                        await clientStream.WriteAsync(answerBytes, 0, answerBytes.Length,ct).ConfigureAwait(true);
                        
                    }
                    catch
                    {
                        
                        //a socket error has occured
                        break;
                    }
                }
                client.Close();
                connection_lost();
            }
        }

19 Source : AdminPanelClient.cs
with Apache License 2.0
from AlexWan

public void Process()
        {
            try
            {
                if (!_client.Connected)
                {
                    throw new NetworkInformationException();
                }
                Stream = _client.GetStream();

                while (true)
                {
                    Thread.Sleep(100);
                    CheckTimeOut();
                    try
                    {
                        var message = GetMessage();

                        if (string.IsNullOrEmpty(message))
                        {
                            continue;
                        }

                        var listMessages = message.Split('~');

                        foreach (var msg in listMessages)
                        {
                            if (string.IsNullOrEmpty(msg))
                            {
                                continue;
                            }

                            if (!Authorized)
                            {
                                var res = TryAuthorization(msg, Token);
                                Authorized = res;
                                if (res)
                                {
                                    _tcpServer.Send("auth");
                                }

                                continue;
                            }
                            if (msg == "ping")
                            {
                                _lastMessageTime = DateTime.Now;
                                continue;
                            }
                            _tcpServer.HandleClientMessage(msg);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            finally
            {
                _tcpServer.RemoveConnection(this.Id);
                Close();
            }
        }

19 Source : ProxyClient.cs
with Apache License 2.0
from AlexWan

private bool Connect(string ip, string port, string token)
        {
            if (_client == null)
            {
                _client = new TcpClient();
            }
            
            try
            {
                _client.Connect(ip, Convert.ToInt32(port));
            }
            catch (Exception e)
            {
                Close();
                Thread.Sleep(500);
                return false;
            }
            
            _stream = _client.GetStream();

            while (!_client.Connected)
            {
                Thread.Sleep(500);
            }
            if (_client.Connected)
            {
                StartListen();
                var message = $"{{\"Token\":\"{token}\"}}";
                Send(message);
                return true;
            }

            return false;
        }

19 Source : ProxyClient.cs
with Apache License 2.0
from AlexWan

private void StartListen()
        {
            Task.Run(() =>
            {
                try
                {
                    while (Connected())
                    {
                        byte[] data = new byte[1024];
                        StringBuilder builder = new StringBuilder();
                        int bytes = 0;
                        do
                        {
                            bytes = _stream.Read(data, 0, data.Length);
                            builder.Append(Encoding.UTF8.GetString(data, 0, bytes));
                        } while (_client.GetStream().DataAvailable);

                        for (int i = 0; i < builder.Length; i++)
                        {
                            if (builder[i] != '~')
                            {
                                _stringBuilder.Append(builder[i]);
                            }
                            else
                            {
                                HandleData(_stringBuilder.ToString());
                                _stringBuilder = new StringBuilder(1024);
                            }
                        }
                    }
                }
                finally
                {
                    Close();
                }
            });
        }

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

public void Process()
        {
            try
            {
                if (!_client.Connected)
                {
                    throw new NetworkInformationException();
                }
                Stream = _client.GetStream();

                while (true)
                {
                    Thread.Sleep(1000);
                    CheckTimeOut();
                    try
                    {
                        var message = GetMessage();

                        if (string.IsNullOrEmpty(message))
                        {
                            continue;
                        }

                        var listMessages = message.Split('~');

                        foreach (var msg in listMessages)
                        {
                            if (string.IsNullOrEmpty(msg))
                            {
                                continue;
                            }

                            if (!Authorized)
                            {
                                var res = TryAuthorization(msg, Token);
                                Authorized = res;
                                if (res)
                                {
                                    _tcpServer.Send("auth");
                                }
                                
                                continue;
                            }
                            if (msg == "ping")
                            {
                                _lastMessageTime = DateTime.Now;
                                continue;
                            }
                            _tcpServer.HandleClientMessage(msg);
                        }
                    }
                    catch (Exception e)
                    {
                        break;
                    }
                }
            }
            finally
            {
                _tcpServer.RemoveConnection(this.Id);
                Close();
            }
        }

19 Source : TorrentClient.cs
with MIT License
from aljazsim

private void Listen()
        {
            int timeout = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
            int bufferSize = 1024 * 1024;
            int bytesRead;
            int offset = 0;
            byte[] buffer = new byte[bufferSize];
            TcpClient tcp;
            TransferManager transfer;

            while (!this.IsDisposed &&
                   this.IsRunning)
            {
                tcp = this.server.AcceptTcpClient();
                tcp.Client.SendTimeout = timeout;
                tcp.SendBufferSize = bufferSize;
                tcp.Client.ReceiveTimeout = timeout;
                tcp.ReceiveBufferSize = bufferSize;

                offset = 0;

                try
                {
                    bytesRead = tcp.GetStream().Read(buffer, 0, buffer.Length);

                    if (bytesRead > 0)
                    {
                        foreach (var message in PeerMessage.Decode(buffer, ref offset, bytesRead))
                        {
                            if (message is HandshakeMessage)
                            {
                                lock (((IDictionary)this.transfers).SyncRoot)
                                {
                                    if (this.transfers.TryGetValue(message.As<HandshakeMessage>().InfoHash, out transfer))
                                    {
                                        transfer.AddLeecher(tcp, message.As<HandshakeMessage>().PeerId);
                                    }
                                    else
                                    {
                                        Debug.WriteLine($"invalid torrent info hash: {message.As<HandshakeMessage>().InfoHash} received");
                                    }
                                }
                            }
                        }
                    }
                }
                catch (IOException ex)
                {
                    // something is wrong with remote peer -> ignore it
                    Debug.WriteLine($"could not read stream from {tcp.Client.RemoteEndPoint}: {ex.Message}");

                    // close the connection
                    tcp.Close();
                    tcp = null;
                }
            }
        }

19 Source : SocketListener.cs
with MIT License
from amazingalek

private void ListenToSocket()
		{
			var localAddress = IPAddress.Parse(Constants.LocalAddress);

			_server = new TcpListener(localAddress, _port);
			_server.Start();

			var bytes = new byte[BufferSize];

			while (true)
			{
				var client = _server.AcceptTcpClient();

				ConsoleUtils.WriteByType(MessageType.Success, "Console connected to socket!");

				var stream = client.GetStream();

				int i;

				while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
				{
					ProcessMessage(bytes, i);
				}

				ConsoleUtils.WriteByType(MessageType.Success, "Closing client!");
				client.Close();
			}
		}

19 Source : OpenVPNSession.cs
with GNU General Public License v3.0
from Amebis

protected override void DoRun()
        {
            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
            try
            {
                try
                {
                    // Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
                    var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
                    mgmtServer.Start();
                    try
                    {
                        try
                        {
                            // Purge stale log files.
                            var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
                            foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
                            {
                                SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
                                if (File.GetLastWriteTimeUtc(f) <= timestamp)
                                {
                                    try { File.Delete(LogPath); }
                                    catch { }
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception) { /* Failure to remove stale log files is not fatal. */ }

                        try
                        {
                            // Save OpenVPN configuration file.
                            using (var fs = new FileStream(
                                ConfigurationPath,
                                FileMode.Create,
                                FileAccess.Write,
                                FileShare.Read,
                                1048576,
                                FileOptions.SequentialScan))
                            using (var sw = new StreamWriter(fs))
                            {
                                // Save profile's configuration to file.

                                if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
                                {
                                    // Remove options on the OpenVPNRemoveOptions list on the fly.
                                    using (var sr = new StringReader(ProfileConfig))
                                    {
                                        string inlineTerm = null;
                                        bool inlineRemove = false;
                                        for (; ; )
                                        {
                                            var line = sr.ReadLine();
                                            if (line == null)
                                                break;

                                            var trimmedLine = line.Trim();
                                            if (!string.IsNullOrEmpty(trimmedLine))
                                            {
                                                // Not an empty line.
                                                if (inlineTerm == null)
                                                {
                                                    // Not inside an inline option block = Regular parsing mode.
                                                    if (!trimmedLine.StartsWith("#") &&
                                                        !trimmedLine.StartsWith(";"))
                                                    {
                                                        // Not a comment.
                                                        var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
                                                        if (option.Count > 0)
                                                        {
                                                            if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
                                                            {
                                                                // Start of an inline option.
                                                                var o = option[0].Substring(1, option[0].Length - 2);
                                                                inlineTerm = "</" + o + ">";
                                                                inlineRemove = openVPNRemoveOptions.Contains(o);
                                                                if (inlineRemove)
                                                                {
                                                                    sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                    line = "# " + line;
                                                                }
                                                            }
                                                            else if (openVPNRemoveOptions.Contains(option[0]))
                                                            {
                                                                sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                line = "# " + line;
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    // Inside an inline option block.
                                                    if (inlineRemove)
                                                    {
                                                        // Remove the inline option content.
                                                        line = "# " + line;
                                                    }

                                                    if (trimmedLine == inlineTerm)
                                                    {
                                                        // Inline option terminator found. Returning to regular parsing mode.
                                                        inlineTerm = null;
                                                    }
                                                }
                                            }

                                            sw.WriteLine(line);
                                        }
                                    }
                                }
                                else
                                    sw.Write(ProfileConfig);

                                // Append eduVPN Client specific configuration directives.
                                sw.WriteLine();
                                sw.WriteLine();
                                sw.WriteLine("# eduVPN Client for Windows");

                                // Introduce ourself (to OpenVPN server).
                                var replacedembly = replacedembly.GetExecutingreplacedembly();
                                var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
                                var replacedemblyVersion = replacedembly?.GetName()?.Version;
                                sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));

                                // Configure log file (relative to WorkingFolder).
                                sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));

                                // Configure interaction between us and openvpn.exe.
                                sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
                                sw.WriteLine("management-client");
                                sw.WriteLine("management-hold");
                                sw.WriteLine("management-query-preplacedwords");
                                sw.WriteLine("management-query-remote");

                                // Configure client certificate.
                                sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
                                sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));

                                // Ask when username/preplacedword is denied.
                                sw.WriteLine("auth-retry interact");
                                sw.WriteLine("auth-nocache");

                                // Set Wintun interface to be used.
                                sw.Write("windows-driver wintun\n");
                                sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");

#if DEBUG
                                // Renegotiate data channel every 5 minutes in debug versions.
                                sw.WriteLine("reneg-sec 300");
#endif

                                if (Environment.OSVersion.Version < new Version(6, 2))
                                {
                                    // Windows 7 is using tiny 8kB send/receive socket buffers by default.
                                    // Increase to 64kB which is default from Windows 8 on.
                                    sw.WriteLine("sndbuf 65536");
                                    sw.WriteLine("rcvbuf 65536");
                                }

                                var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
                                if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
                                {
                                    sw.WriteLine();
                                    sw.WriteLine();
                                    sw.WriteLine("# Added by OpenVPNAddOptions setting:");
                                    sw.WriteLine(openVPNAddOptions);
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }

                        bool retry;
                        do
                        {
                            retry = false;

                            // Connect to OpenVPN Interactive Service to launch the openvpn.exe.
                            using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
                            {
                                var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
                                try
                                {
                                    openvpnInteractiveServiceConnection.Connect(
                                        string.Format("openvpn{0}\\service", InstanceName),
                                        WorkingFolder,
                                        new string[] { "--config", ConnectionId + ".conf", },
                                        mgmtPreplacedword + "\n",
                                        3000,
                                        SessionAndWindowInProgress.Token);
                                }
                                catch (OperationCanceledException) { throw; }
                                catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }

                                try
                                {
                                    // Wait and accept the openvpn.exe on our management interface (--management-client parameter).
                                    var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
                                    try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
                                    catch (AggregateException ex) { throw ex.InnerException; }
                                    var mgmtClient = mgmtClientTask.Result;
                                    try
                                    {
                                        // Start the management session.
                                        ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);

                                        // Initialize session and release openvpn.exe to get started.
                                        ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
                                        ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
                                        ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
                                        ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);

                                        Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
                                        try
                                        {
                                            // Wait for the session to end gracefully.
                                            ManagementSession.Monitor.Join();
                                            if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
                                            {
                                                // Session reported an error. Retry.
                                                retry = true;
                                            }
                                        }
                                        finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
                                    }
                                    finally { mgmtClient.Close(); }
                                }
                                finally
                                {
                                    Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                                        () =>
                                        {
                                            // Cleanup status properties.
                                            State = SessionStatusType.Disconnecting;
                                            StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
                                            TunnelAddress = null;
                                            IPv6TunnelAddress = null;
                                            ConnectedAt = null;
                                            BytesIn = null;
                                            BytesOut = null;
                                        }));

                                    // Wait for openvpn.exe to finish. Maximum 30s.
                                    try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
                                    catch (ArgumentException) { }
                                }
                            }
                        } while (retry);
                    }
                    finally
                    {
                        mgmtServer.Stop();
                    }
                }
                finally
                {
                    // Delete profile configuration file. If possible.
                    try { File.Delete(ConfigurationPath); }
                    catch { }
                }
            }
            finally
            {
                Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
                    () =>
                    {
                        // Cleanup status properties.
                        State = SessionStatusType.Disconnected;
                        StateDescription = "";

                        Wizard.TaskCount--;
                    }));
                PropertyUpdater.Stop();
            }
        }

19 Source : ModbusServer.cs
with MIT License
from AndreasAmMueller

private async Task HandleClient(TcpClient client)
		{
			logger?.LogTrace("ModbusServer.HandleClient enter");
			var endpoint = (IPEndPoint)client.Client.RemoteEndPoint;
			try
			{
				ClientConnected?.Invoke(this, new ClientEventArgs(endpoint));
				logger?.LogInformation($"Client connected: {endpoint.Address}.");

				var stream = client.GetStream();
				while (!stopCts.IsCancellationRequested)
				{
					using var requestStream = new MemoryStream();

					using (var cts = new CancellationTokenSource(Timeout))
					using (stopCts.Token.Register(() => cts.Cancel()))
					{
						try
						{
							byte[] header = await stream.ReadExpectedBytes(6, cts.Token);
							await requestStream.WriteAsync(header, 0, header.Length, cts.Token);

							byte[] bytes = header.Skip(4).Take(2).ToArray();
							if (BitConverter.IsLittleEndian)
								Array.Reverse(bytes);

							int following = BitConverter.ToUInt16(bytes, 0);
							byte[] payload = await stream.ReadExpectedBytes(following, cts.Token);
							await requestStream.WriteAsync(payload, 0, payload.Length, cts.Token);
						}
						catch (OperationCanceledException) when (cts.IsCancellationRequested)
						{
							continue;
						}
					}

					try
					{
						var request = new Request(requestStream.GetBuffer());
						var response = requestHandler?.Invoke(request, stopCts.Token);
						if (response != null)
						{
							using var cts = new CancellationTokenSource(Timeout);
							using var reg = stopCts.Token.Register(() => cts.Cancel());
							try
							{
								byte[] bytes = response.Serialize();
								await stream.WriteAsync(bytes, 0, bytes.Length, cts.Token);
							}
							catch (OperationCanceledException) when (cts.IsCancellationRequested)
							{
								continue;
							}
						}
					}
					catch (ArgumentException ex)
					{
						logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
					}
					catch (NotImplementedException ex)
					{
						logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
					}
				}
			}
			catch (IOException)
			{
				// client connection closed
				return;
			}
			catch (Exception ex)
			{
				logger?.LogError(ex, $"Unexpected error ({ex.GetType().Name}) occurred: {ex.GetMessage()}");
			}
			finally
			{
				ClientDisconnected?.Invoke(this, new ClientEventArgs(endpoint));
				logger?.LogInformation($"Client disconnected: {endpoint.Address}");

				client.Dispose();
				tcpClients.TryRemove(client, out _);

				logger?.LogTrace("ModbusServer.HandleClient leave");
			}
		}

19 Source : ModbusClient.cs
with MIT License
from AndreasAmMueller

private async Task Reconnect()
		{
			try
			{
				logger?.LogTrace("ModbusClient.Reconnect enter");
				lock (reconnectLock)
				{
					if (isReconnecting || stopCts.IsCancellationRequested)
						return;

					isReconnecting = true;
					IsConnected = false;
				}

				logger?.LogInformation($"{(wasConnected ? "Rec" : "C")}onnect starting.");
				if (wasConnected)
				{
					receiveCts?.Cancel();
					await receiveTask;
					receiveCts = null;
					receiveTask = Task.CompletedTask;
					Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
				}

				var timeout = TimeSpan.FromSeconds(2);
				var startTime = DateTime.UtcNow;

				var address = ResolveHost(Host);
				while (!stopCts.IsCancellationRequested)
				{
					try
					{
						stream?.Dispose();
						stream = null;

						tcpClient?.Dispose();
						tcpClient = new TcpClient(address.AddressFamily);

						var connectTask = tcpClient.ConnectAsync(address, Port);
						if (await Task.WhenAny(connectTask, Task.Delay(timeout, stopCts.Token)) == connectTask && tcpClient.Connected)
						{
							SetKeepAlive();
							stream = tcpClient.GetStream();

							receiveCts = new CancellationTokenSource();
							receiveTask = Task.Run(async () => await ReceiveLoop());

							lock (reconnectLock)
							{
								IsConnected = true;
								wasConnected = true;

								reconnectTcs?.TrySetResult(true);
								Task.Run(() => Connected?.Invoke(this, EventArgs.Empty)).Forget();
							}
							logger?.LogInformation($"{(wasConnected ? "Rec" : "C")}onnected successfully.");
							return;
						}
						else
						{
							if (timeout < MaxConnectTimeout)
							{
								logger?.LogWarning($"{(wasConnected ? "Rec" : "C")}onnect failed within {timeout}.");
								timeout = timeout.Add(TimeSpan.FromSeconds(2));
								if (timeout > MaxConnectTimeout)
									timeout = MaxConnectTimeout;
							}
							throw new SocketException((int)SocketError.TimedOut);
						}
					}
					catch (SocketException) when (ReconnectTimeSpan == TimeSpan.MaxValue || DateTime.UtcNow - startTime <= ReconnectTimeSpan)
					{
						await Task.Delay(1000, stopCts.Token);
						continue;
					}
					catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
					{
						throw;
					}
					catch (Exception ex)
					{
						logger?.LogError(ex, $"{(wasConnected ? "Rec" : "C")}onnecting failed: {ex.GetMessage()}, trying again.");
					}
				}
			}
			catch (OperationCanceledException) when (stopCts.IsCancellationRequested)
			{
				reconnectTcs?.TrySetCanceled();
			}
			catch (Exception ex)
			{
				logger?.LogError(ex, $"{(wasConnected ? "Rec" : "C")}onnecting failed: {ex.GetMessage()}");
				reconnectTcs?.TrySetException(ex);
			}
			finally
			{
				lock (reconnectLock)
				{
					isReconnecting = false;
					reconnectTcs = null;
				}
				logger?.LogTrace("ModbusClient.Reconnect leave");
			}
		}

19 Source : ModbusTcpTests.cs
with MIT License
from AndreasAmMueller

private async Task RunServer(CancellationToken ct)
			{
				while (!ct.IsCancellationRequested)
				{
					try
					{
						var client = await listener.AcceptTcpClientAsync();
						try
						{
							var clientEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;

							using var stream = client.GetStream();

							SpinWait.SpinUntil(() => stream.DataAvailable || ct.IsCancellationRequested);
							if (ct.IsCancellationRequested)
							{
								Console.WriteLine("Server cancel => WaitData");
								return;
							}

							byte[] buffer = new byte[100];
							var bytes = new List<byte>();
							do
							{
								int count = await stream.ReadAsync(buffer, 0, buffer.Length, ct);
								bytes.AddRange(buffer.Take(count));
							}
							while (stream.DataAvailable && !ct.IsCancellationRequested);

							if (ct.IsCancellationRequested)
							{
								Console.WriteLine("Server cancel => DataRead");
								return;
							}

							Debug.WriteLine($"Server data read done: {bytes.Count} bytes");
							if (RequestHandler != null)
							{
								Console.WriteLine("Server send RequestHandler");
								try
								{
									byte[] response = RequestHandler(bytes.ToArray(), clientEndPoint);
									Console.WriteLine($"Server response: {response?.Length ?? -1}");
									if (response != null)
									{
										await stream.WriteAsync(response, 0, response.Length, ct);
										Console.WriteLine("Server response written");
									}
								}
								catch (Exception ex)
								{
									LastError = ex.GetMessage();
								}
							}
						}
						finally
						{
							client?.Dispose();
						}
					}
					catch (OperationCanceledException) when (ct.IsCancellationRequested)
					{ }
					catch (ObjectDisposedException) when (ct.IsCancellationRequested)
					{ }
					catch (Exception ex)
					{
						string msg = ex.GetMessage();
						Console.WriteLine($"Server exception: " + msg);
					}
				}
			}

19 Source : CheatEngineServer.cs
with GNU General Public License v3.0
from andreluis034

private void HandleReceivedClient(TcpClient client)
        {
            var clientStream = client.GetStream();
            var reader = new BinaryReader(clientStream);
            var writer = new BinaryWriter(clientStream);
            while (true)
            {
                try
                {

                    var command = this.packetManager.ReadNextCommand(reader);
                    var output = this.packetManager.ProcessAndGetBytes(command);
                    /* if(command.CommandType != CommandType.CMD_READPROCESSMEMORY)
                         Console.WriteLine(BitConverter.ToString(output).Replace("-", ""));*/
                   // Console.WriteLine("{0} returned {1} bytes", command.CommandType, output.Length);
                    writer.Write(output);
                    writer.Flush();
                    //   Handle(stream, writer, cmd);

                }
                catch(EndOfStreamException)
                {
                    client.Close();
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e + ": "+  e.Message);
                    Console.WriteLine(e.StackTrace);
                    client.Close();
                    break;
                } 
            }
        }

19 Source : Printer.cs
with MIT License
from andycb

public async Task ConnectAsync()
        {
            await this.printerConnection.ConnectAsync(this.printerAddress, 8899).ConfigureAwait(false);
            this.streamWriter = new StreamWriter(this.printerConnection.GetStream()) { AutoFlush = true };
            this.streamReader = new StreamReader(this.printerConnection.GetStream());
            this.responseReader = new PrinterResponseReader(this.printerConnection.GetStream());

            // The printer does not respond until the status is first requested, so do that now.
            await this.GetPrinterStatusAsync();
        }

19 Source : Printer.cs
with MIT License
from andycb

public async Task StoreFileAsync(string filePath, string fileName)
        {
            this.ValidatePrinterReady();

            var modelBytes = File.ReadAllBytes(filePath);

            // Start a transfer
            this.streamWriter.WriteLine(string.Format(CultureInfo.InvariantCulture, "~{0} {1} 0:/user/{2}", MachineCommands.BeginWriteToSdCard, modelBytes.Count(), fileName));
            await this.WaitForPrinterAck().ConfigureAwait(false);

            var crcAlg = new Crc32Algorithm(!BitConverter.IsLittleEndian);

            var count = 0;
            int offset = 0;
            var printerStream = this.printerConnection.GetStream();
            while (offset < modelBytes.Length)
            {
                uint crc;
                byte[] packet = new byte[packetSizeBytes];
                var dataSize = 0u;
                if (offset + packetSizeBytes < modelBytes.Length)
                {
                    packet = modelBytes.Skip(offset).Take(packetSizeBytes).ToArray();
                    var crcBytes = BitConverter.ToUInt32(crcAlg.ComputeHash(packet));
                    crc = GetBigEndian(crcBytes);
                    dataSize = packetSizeBytes;
                }
                else
                {
                    // Every packet needs to be the same size, so zero pad the last one if we need to.
                    var actualLength = modelBytes.Length - offset;
                    var data = modelBytes.Skip(offset).Take(actualLength).ToArray();

                    // The CRC is for the un-padded data.
                    var crcBytes = BitConverter.ToUInt32(crcAlg.ComputeHash(data));
                    crc = GetBigEndian(crcBytes);

                    Array.Copy(data, 0, packet, 0, actualLength);
                    Array.Fill<byte>(packet, 0x0, actualLength, packetSizeBytes - actualLength);
                    dataSize = (uint)actualLength;
                }

                var packetToSend = new List<byte>();

                // Always start each packet with four bytes
                packetToSend.AddRange(this.fileTransferPrefixBytes);

                // Add the count of this packet, the size of the data it in (not counting padding) and the CRC.
                packetToSend.AddRange(BitConverter.GetBytes(GetBigEndian((uint)count)));
                packetToSend.AddRange(BitConverter.GetBytes(GetBigEndian(dataSize)));
                packetToSend.AddRange(BitConverter.GetBytes(crc));

                // Finally add thr actual data
                packetToSend.AddRange(packet);

                // Send the data
                printerStream.Write(packetToSend.ToArray());
                printerStream.Flush();

                offset += packetSizeBytes;
                ++count;
            }

            // Tell the printer that we have finished sending the file.
            this.streamWriter.WriteLine(string.Format(CultureInfo.InvariantCulture, "~{0}", MachineCommands.EndWriteToSdCard));
            await this.WaitForPrinterAck();
        }

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

private void BeginAccept()
        {
            lock (this)
            {
                if (this.server == null ||
                    this.isStoping)
                {
                    return;
                }

                this.server?.BeginAcceptTcpClient((result) =>
                {
                    try
                    {
                        lock (this)
                        {
                            if (this.server == null ||
                                this.isStoping)
                            {
                                return;
                            }

                            Thread.Sleep(10);

                            using (var client = this.server?.EndAcceptTcpClient(result))
                            using (var ns = client?.GetStream())
                            {
                                this.ProcessMessage(ns);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        this.Logger.Error(ex, $"Boyomi TCP server error.");
                    }
                    finally
                    {
                        this.BeginAccept();
                    }
                },
                this.server);
            }
        }

19 Source : BoyomiClient.cs
with MIT License
from anoyetta

private void Send(
            string tts)
        {
            var server = Config.Instance.TTSServerAddress;
            var port = Config.Instance.TTSServerPort;

            if (string.IsNullOrEmpty(server))
            {
                AppLogger.Error("TTS Server address is empty.");
                return;
            }

            if (port > 65535 ||
                port < 1)
            {
                AppLogger.Error("TTS Server port is invalid.");
                return;
            }

            if (server.ToLower() == "localhost")
            {
                server = "127.0.0.1";
            }

            try
            {
                lock (this)
                {
                    using (var tcp = new TcpClient(server, port))
                    using (var ns = tcp.GetStream())
                    using (var buffer = new MemoryStream())
                    using (var bw = new BinaryWriter(buffer))
                    {
                        var messageAsBytes = Encoding.UTF8.GetBytes(tts);

                        bw.Write(BoyomiCommand);
                        bw.Write((short)Config.Instance.TTSSpeed);
                        bw.Write(BoyomiTone);
                        bw.Write((short)Config.Instance.TTSVolume);
                        bw.Write(BoyomiVoice);
                        bw.Write(BoyomiTextEncoding);
                        bw.Write(messageAsBytes.Length);
                        bw.Write(messageAsBytes);
                        bw.Flush();

                        ns.Write(buffer.ToArray(), 0, (int)buffer.Length);
                        ns.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                AppLogger.Error("Exception occurred when sending to the TTS server.", ex);
            }
        }

19 Source : SmartHomeProtocolMessage.cs
with Apache License 2.0
from anthturner

internal dynamic Execute(string hostname, int port)
        {
            var messageToSend = SmartHomeProtocolEncoder.Encrypt(JSON);

            var client = new TcpClient(hostname, port);
            byte[] packet = new byte[0];
            using (var stream = client.GetStream())
            {
                stream.Write(messageToSend, 0, messageToSend.Length);

                int targetSize = 0;
                var buffer = new List<byte>();
                while (true)
                {
                    var chunk = new byte[1024];
                    var bytesReceived = stream.Read(chunk, 0, chunk.Length);

                    if (!buffer.Any())
                    {
                        var lengthBytes = chunk.Take(4).ToArray();
                        if (BitConverter.IsLittleEndian) // this value needs to be in big-endian
                            lengthBytes = lengthBytes.Reverse().ToArray();
                        targetSize = (int)BitConverter.ToUInt32(lengthBytes, 0);
                    }
                    buffer.AddRange(chunk.Take(bytesReceived));

                    if (buffer.Count == targetSize + 4)
                        break;
                }

                packet = buffer.Skip(4).Take(targetSize).ToArray();
            }
            client.Close();

            var decrypted = Encoding.UTF8.GetString(SmartHomeProtocolEncoder.Decrypt(packet)).Trim('\0');

            var subResult = (dynamic)((JObject)JObject.Parse(decrypted)[System])[Command];
            if (subResult["err_code"] != null && subResult.err_code != 0)
                throw new Exception($"Protocol error {subResult.err_code} ({subResult.err_msg})");

            return subResult;
        }

19 Source : Connector.cs
with Apache License 2.0
from apache

private static async Task<Stream> GetStream(string host, int port)
    {
        var tcpClient = new TcpClient();

        try
        {
            var type = Uri.CheckHostName(host);

            if (type == UriHostNameType.IPv4 || type == UriHostNameType.IPv6)
                await tcpClient.ConnectAsync(IPAddress.Parse(host), port).ConfigureAwait(false);
            else
                await tcpClient.ConnectAsync(host, port).ConfigureAwait(false);

            return tcpClient.GetStream();
        }
        catch
        {
            tcpClient.Dispose();
            throw;
        }
    }

19 Source : ModbusTcpClient.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

public void Connect(IPEndPoint remoteEndpoint, ModbusEndianness endianness)
        {
            base.SwapBytes = BitConverter.IsLittleEndian && endianness == ModbusEndianness.BigEndian
                         || !BitConverter.IsLittleEndian && endianness == ModbusEndianness.LittleEndian;

            _frameBuffer = new ModbusFrameBuffer(260);

            _tcpClient?.Close();
            _tcpClient = new TcpClient();

            if (!_tcpClient.ConnectAsync(remoteEndpoint.Address, remoteEndpoint.Port).Wait(this.ConnectTimeout))
                throw new Exception(ErrorMessage.ModbusClient_TcpConnectTimeout);

            _networkStream = _tcpClient.GetStream();
            _networkStream.ReadTimeout = this.ReadTimeout;
            _networkStream.WriteTimeout = this.WriteTimeout;
        }

See More Examples