TcpListener Class : TCP Server « Network « C# / C Sharp






TcpListener Class

 

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

class MyTcpListener
{
  public static void Main()
  { 
    TcpListener server=null;   
    try
    {
      server = new TcpListener(IPAddress.Parse("127.0.0.1"), 13000);
      server.Start();
      Byte[] bytes = new Byte[256];
      String data = null;
      while(true) 
      {
        TcpClient client = server.AcceptTcpClient();            
        Console.WriteLine("Connected!");
        data = null;
        NetworkStream stream = client.GetStream();
        int i;
        while((i = stream.Read(bytes, 0, bytes.Length))!=0) 
        {   
          data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
          Console.WriteLine(data);
          data = data.ToUpper();
          byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
          stream.Write(msg, 0, msg.Length);
          Console.WriteLine("Sent: {0}", data);            
        }
        client.Close();
      }
    }
    catch(SocketException e)
    {
      Console.WriteLine("SocketException: {0}", e);
    }
    finally
    {
       server.Stop();
    }
    Console.WriteLine("\nHit enter to continue...");
    Console.Read();
  }   
}

   
  








Related examples in the same category

1.Bad Tcp ServerBad Tcp Server
2.Fixed Tcp Server
3.Stream Tcp Server
4.Simple Tcp Server
5.Var Tcp Server
6.Employee Server
7.Network Order Server
8.Tcp Listener Sample
9.Async Tcp ServerAsync Tcp Server
10.Select Tcp Server
11.Tcp Poll Server
12.Threaded Tcp Server
13.Picky Tcp Listener
14.Accepts a pending connection request