Communicate Using TCP - CSharp Network

CSharp examples for Network:TCP

Description

Communicate Using TCP

Demo Code

using System;//from   w  ww  . ja  v a 2 s  .c om
using System.IO;
using System.Net;
using System.Net.Sockets;
class MainClass
{
   public static void Main()
   {
      TcpClient client = new TcpClient();
      try
      {
         Console.WriteLine("Attempting to connect to the server ", "on port 8000.");
         client.Connect(IPAddress.Parse("127.0.0.1"), 8000);
         Console.WriteLine("Connection established.");
         NetworkStream stream = client.GetStream();
         using (BinaryWriter w = new BinaryWriter(stream))
         {
            using (BinaryReader r = new BinaryReader(stream))
            {
               w.Write("RequestConnect");
               if (r.ReadString() == "OK")
               {
                  Console.WriteLine("Connected.");
                  Console.WriteLine("Press Enter to disconnect.");
                  Console.ReadLine();
                  Console.WriteLine("Disconnecting...");
                  w.Write("Disconnect");
               }
               else
               {
                  Console.WriteLine("Connection not completed.");
               }
            }
         }
      }
      catch (Exception err)
      {
         Console.WriteLine(err.ToString());
      }
      finally
      {
         // Close the connection socket.
         client.Close();
         Console.WriteLine("Port closed.");
      }
   }
}

Result


Related Tutorials