tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

TcpListener and TcpClient (an easy-to-use example)

21 Jun 2005 1 mins .NET

Follow-up post.

During the weekend I needed some tool: Have to be able to listen on some port and to do something “useful”. First I was trying to use sockets. But I’ve found useful classes: TcpListener and TcpClient. It was exactly what I was looking for. Here you can “taste” the example.

using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;

namespace port_listen
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Console.WriteLine("Starting...");
      TcpListener server = new TcpListener(IPAddress.Parse("0.0.0.0"), 66);
      server.Start();
      Console.WriteLine("Started.");
      while (true)
      {
        ClientWorking cw = new ClientWorking(server.AcceptTcpClient());
        new Thread(new ThreadStart(cw.DoSomethingWithClient)).Start();
      }
      server.Stop();
    }
  }

  class ClientWorking
  {
    private Stream ClientStream;
    private TcpClient Client;

    public ClientWorking(TcpClient Client)
    {
      this.Client = Client;
      ClientStream = Client.GetStream();
    }

    public void DoSomethingWithClient()
    {
      StreamWriter sw = new StreamWriter(ClientStream);
      StreamReader sr = new StreamReader(sw.BaseStream);
      sw.WriteLine("Hi. This is x2 TCP/IP easy-to-use server");
      sw.Flush();
      string data;
      try
      {
        while ((data = sr.ReadLine()) != "exit")
        {
          sw.WriteLine(data);
          sw.Flush();
        }
      }
      finally
      {
        sw.Close();
      }
    }
  }
}

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.