21
Jun

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

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();
      }
    }
  }
}

There's 3 Comments So Far

  • Boris Letocha
    June 21st, 2005 at 20:22

    And for which reason is there server.Stop()? :-)

  • cincura.net
    December 9th, 2005 at 17:22

    Umm, the inertia. :)

    But you can extened the server for stopping. ;)

  • Anurag Srivastava
    July 22nd, 2011 at 22:02

    Thanks a lot brother. Pretty simple to use and worked at first go. I saved a lot of time using this.

    Thanks again!!

Share your thoughts, leave a comment!