Skip to content

Instantly share code, notes, and snippets.

@Phyyl
Created September 10, 2015 15:17
Show Gist options
  • Save Phyyl/c18eb5bdd8e219c0eb14 to your computer and use it in GitHub Desktop.
Save Phyyl/c18eb5bdd8e219c0eb14 to your computer and use it in GitHub Desktop.
        static void Main(string[] args)
        {
            Console.WriteLine("Local addresses: ");
            foreach (var address in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                Console.WriteLine($"    {address}");
            }
            TcpListener listener = new TcpListener(IPAddress.Any, 30000);
            listener.Start();
            AcceptClientsAsync(listener);
            while (true) ;
        }
        static async void AcceptClientsAsync(TcpListener listener)
        {
            while(true)
            {
                Console.WriteLine($"Listening...");
                TcpClient client = await listener.AcceptTcpClientAsync();
                ReceiveDataAsync(client);
            }
        }
        static async void ReceiveDataAsync(TcpClient client)
        {
            IPEndPoint endpoint = (IPEndPoint)client.Client.RemoteEndPoint;
            StreamReader reader = new StreamReader(client.GetStream());
            Console.WriteLine($"Client connected from {endpoint}");
            
            while (client.Connected)
            {
                string line = await reader.ReadLineAsync();
                if (line == null)
                {
                    break;
                }
                Console.WriteLine($"{endpoint}: {line}");
            }
            Console.WriteLine($"Client disconnected from {endpoint}");
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment