Wednesday, December 11, 2013

Basic TCP socket echo client server program in C#


Here we will create a simple echo client and echo server program where client send the message string to the server and server echoed back the same message string to the client. Download the both client and server source code compile it and run both in command window. IP address , port and message are passed through command line argument.

Download Source Code

You can download the complete source code form below.

Explaining the Code

Let starts digging the code.
At first we will discuss the echo client program.
Server name or Ip address, message  and port is passed in command line argument to create Tcp socket and establish the connection with server.
First, we check the number of argument passed. First two argument is compulsory and third argument is optional.
if ((args.Length < 2) || (args.Length > 3)) { // Test for correct # of args
      throw new ArgumentException("Parameters:   []");
First argument args[0 ]is Ip address or server name .Second argument agrs[1] is input message string with is converted to byte stream . Third argument agrs[2] is optional to define port number with default value 7 and it is converted from string to integer.
    String server = args[0];  // Server name or IP address

    // Convert input String to bytes 
    byte[] byteBuffer = Encoding.ASCII.GetBytes(args[1]);

    // Use port argument if supplied, otherwise default to 7
    int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7;
Create TcpClient and NetworkStream object.
TcpClient client = null;
NetworkStream netStream = null;
Create socket for connecting to the server in specified port.
client = new TcpClient(server, servPort);
Return network stream to send and receive the message data and Send the message data to the server using Write method. First parameter of Write method is an array of type Byte that contains the data to write to the NetworkStream.
      // Create socket that is connected to server on specified port
      client = new TcpClient(server, servPort);

      Console.WriteLine("Connected to server... sending echo string");
      netStream = client.GetStream();

      // Send the encoded string to the server
      netStream.Write(byteBuffer, 0, byteBuffer.Length);
Up to this point we created a socket to connect server and send message string to the server through NetworkStream.
Now, we will receive the reply from the server. As same send message string by client is echoed back by the server we already know the number of byte to receive from server. Read methods is used to received the bytes and it takes three parameters (1)an array of type Byte that is the location in memory to store data read from the NetworkStream  (2) The location in buffer to begin storing the data to (3) The number of bytes to read from the NetworkStream.
      // Receive the same string back from the server
      while (totalBytesRcvd < byteBuffer.Length) {
        if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd, 
                byteBuffer.Length - totalBytesRcvd)) == 0) {
          Console.WriteLine("Connection closed prematurely.");
        totalBytesRcvd += bytesRcvd;

Create the TcpListener to accept the client connection using  TcpListener class. Here TcpListener constructor takes two parameters (1) An IPAddress that represents the local IP address. (2) The port on which to listen for incoming connection attempts. First parameter is IPAddress.Any which means server can connect with client having any IPAddress. After that use Start() method to begin listening from incoming connection request.
// Create a TCPListener to accept client connections
listener = new TcpListener(IPAddress.Any, servPort);
Server must run the forever to get connection for client. It get the connection with client using AcceptTcpClient method. After connection , server read the message string using Read method and write same message using Write method.
        client = listener.AcceptTcpClient(); // Get client connection
        netStream = client.GetStream();
        Console.Write("Handling client - ");

        // Receive until client closes connection, indicated by 0 return value
        int totalBytesEchoed = 0;
        while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) {
          netStream.Write(rcvBuffer, 0, bytesRcvd);
          totalBytesEchoed += bytesRcvd;

Running the program

At first run the TcpEchoServer at command window:
C:\Users\....>TcpEchoServer.exe                [Press Enter]

Now run the TcpEchoClient at another command window:
C:\Users\....>TcpEchoClient.exe localhost "this is echo message"    [Press Enter]


1 comment:

  1. Very good article... I liked your example.