Socket client in C#

 
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
 
public class clnt {
 
  public static void Main() {
 
    try {
 
      TcpClient tcpclnt = new TcpClient();
      Console.WriteLine("Attempting to connect to server.");
 
      tcpclnt.Connect("127.0.0.1",8001); 
 
      Console.WriteLine("Connected to server.");
      Console.Write("Enter the string to be transmitted: ");
 
      String str=Console.ReadLine();
      Stream stm = tcpclnt.GetStream();
 
      ASCIIEncoding asen= new ASCIIEncoding();
      byte[] ba=asen.GetBytes(str);
      Console.WriteLine("Transmitting...");
 
      stm.Write(ba,0,ba.Length);
 
      byte[] bb=new byte[100];
      int k=stm.Read(bb,0,100);
 
      Console.Write("Server reply: ");
      for (int i=0;i<k;i++) Console.Write(Convert.ToChar(bb[i]));
      Console.WriteLine("  EOT");
 
      tcpclnt.Close();
    } catch (Exception e) { 
      Console.WriteLine("Error: " + e.StackTrace);
    }
  }
 
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.