Create TCP Client - CSharp Network

CSharp examples for Network:TCP

Description

Create TCP Client

Demo Code

using System;/* ww w  .  j  a  v a 2  s.c  o m*/
using System.Net;
using System.Net.Sockets;
using System.IO;
class MainClass
{
   private static void Main()
   {
      using (TcpClient client = new TcpClient())
      {
         Console.WriteLine("Attempting to connect to the server ", "on port 8000.");
         client.Connect(IPAddress.Parse("127.0.0.1"), 8000);
         using (NetworkStream networkStream = client.GetStream())
         {
            using (BinaryWriter writer = new BinaryWriter(networkStream))
            {
               writer.Write("RequestConnect");
               using (BinaryReader reader = new BinaryReader(networkStream))
               {
                  if (reader.ReadString() == "OK")
                  {
                     Console.WriteLine("Connection established." + "Press Enter to download data.");
                     Console.ReadLine();
                     writer.Write("RequestData");
                     int fileSize = int.Parse(reader.ReadString());
                     for (int i = 0; i < fileSize / 3; i++)
                     {
                        Console.Write(networkStream.ReadByte());
                     }
                     Console.WriteLine("Press Enter to disconnect.");
                     Console.ReadLine();
                     Console.WriteLine("Disconnecting...");
                     writer.Write("Disconnect");
                  }
                  else
                  {
                     Console.WriteLine("Connection not established.");
                  }
               }
            }
         }
      }
   }
}

Result


Related Tutorials