Create a new listener on port 8000. - CSharp Network

CSharp examples for Network:TCP

Description

Create a new listener on port 8000.

Demo Code

using System;// ww w .  j a v  a2s  .  c  o m
using System.IO;
using System.Net;
using System.Net.Sockets;
class MainClass
{
   public static void Main()
   {
      // Create a new listener on port 8000.
      TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8000);
      Console.WriteLine("About to initialize port.");
      listener.Start();
      Console.WriteLine("Listening for a connection...");
      try
      {
         using (TcpClient client = listener.AcceptTcpClient())
         {
            Console.WriteLine("Connection accepted.");
            NetworkStream stream = client.GetStream();
            using (BinaryWriter w = new BinaryWriter(stream))
            {
               using (BinaryReader r = new BinaryReader(stream))
               {
                  if (r.ReadString() == "RequestConnect")
                  {
                     w.Write("OK");
                     Console.WriteLine("Connection completed.");
                     while (r.ReadString() != "Disconnect") { }
                        Console.WriteLine(Environment.NewLine);
                     Console.WriteLine("Disconnect request received.");
                  }
                  else
                  {
                     Console.WriteLine("Can't complete connection.");
                  }
               }
            }
         }
         Console.WriteLine("Connection closed.");
      }
      catch (Exception ex)
      {
         Console.WriteLine(ex.ToString());
      }
      finally
      {
         listener.Stop();
         Console.WriteLine("Listener stopped.");
      }
   }

}

Result


Related Tutorials