Simple Tcp Client: send data to the server : Socket Client « Network « C# / CSharp Tutorial






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

class MainClass
{
   public static void Main()
   {
      IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

      Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

      try
      {
         server.Connect(ip);
      } catch (SocketException e){
         Console.WriteLine("Unable to connect to server.");
         return;
      }

      Console.WriteLine("Type 'exit' to exit.");
      while(true)
      {
         string input = Console.ReadLine();
         if (input == "exit")
            break;
         server.Send(Encoding.ASCII.GetBytes(input));
         byte[] data = new byte[1024];
         int receivedDataLength = server.Receive(data);
         string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
         Console.WriteLine(stringData);
      }

      server.Shutdown(SocketShutdown.Both);
      server.Close();
   }
}








33.5.Socket Client
33.5.1.Echo Client without message encoding
33.5.2.Echo Client with UTF8 Encoding
33.5.3.Socket connection
33.5.4.Send data using Socket
33.5.5.Simple Tcp Client: receive data from server
33.5.6.Simple Tcp Client: send data to the server
33.5.7.Simple Tcp server: send data to the client
33.5.8.GUI based Tcp Client