TcpListener Sample : TcpListener « Network « C# / CSharp Tutorial






using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
   public static void Main()
   {
      int receivedDataLength;
      byte[] data = new byte[1024];

      TcpListener socket = new TcpListener(9999);
      socket.Start();

      TcpClient client = socket.AcceptTcpClient();
      NetworkStream ns = client.GetStream();

      string welcome = "Welcome";
      data = Encoding.ASCII.GetBytes(welcome);
      ns.Write(data, 0, data.Length);

      while(true)
      {
         data = new byte[1024];
         receivedDataLength = ns.Read(data, 0, data.Length);
         Console.WriteLine(Encoding.ASCII.GetString(data, 0, receivedDataLength));
         ns.Write(data, 0, receivedDataLength);
      }
      ns.Close();
      client.Close();
      socket.Stop();
   }
}








33.8.TcpListener
33.8.1.Listening for sockets
33.8.2.TcpListener Sample
33.8.3.Create a Socket server from TcpListener
33.8.4.Use NetworkStream to write to a client
33.8.5.Use TcpListener to create a Tcp server
33.8.6.Create BinaryWriter and BinaryReader from TcpListener
33.8.7.Time Server
33.8.8.Asynch Network Server