Understanding Client and Server Communications


Network communication plays a vital role in facilitating the exchange of data and resources between devices. But who are we communicating with? Communication is supposed to be between two people, so who’s on the other side? 

When we fire up a browser or connect to a website, we establish a connection with a server, which is hosted somewhere and allows us to communicate with it. The server then sends data to the incoming receivers, illustrating the fundamental workings of a web server.

This is known as the Client-Server architecture. Here a Client initiates a connection which the server then responds to.

Note: A server can never initiate a connection. It ONLY listens.

But communication on the internet can’t happen without some predefined rules. One of the protocols that define how data is supposed to transfer between clients and servers is called the TCP (Transmission Control Protocol).

TCP ensures reliable, ordered, and error-checked delivery of data between applications running on devices connected to a network.

TCP works on Synchronization and Acknowledgement between the client and server.

The Client first sends a SYNC call to the server to request synchronization. The server then responds back with a confirmation call. The client then sends it’s acknowledgement of the servers’ response and communication can take place.

Creating Web Servers in C#

C# is generally used to create web servers due to its robustness and tools for building web applications. It is based on the .NET framework by Microsoft which also adds to its credibility.

Server: Sending a “Hello” message: 

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

public static class WebServer
{
    public static void Main()
    {
        Console.WriteLine("Web Server Started");

        TcpListener listener = new TcpListener(IPAddress.Any,99);
        listener.Start();

        // creates a connection to accept client requests
        Socket conn = listener.AcceptSocket();
        
        // creates a stream to handle I/O of data
        Stream stream = new NetworkStream(conn);
    
        // Connects to the stream for sending data
        StreamWriter sw = new StreamWriter(stream);

        // This function will send data to the client.
        // So the message below will only show to the client.
        sw.WriteLine("You have connected to the server");
        sw.Flush();
    
        Console.WriteLine("Connected!");

        // closing off all connections.
        stream.Close();
        conn.Close();
    }
}
This code runs a simple web server:
  1. Listens for connections on any IP address (port 99).
  2. Waits for a client to connect.
  3. Opens a communication stream with the client.
  4. Sends a message ("You have connected to the server") to the client.
  5. Confirms the connection on the server side.
  6. Closes the connection
Great, So now we know how a web server works. But we haven’t seen the client side of things here. What happens when a connection is received by the server? What does it see?

The code below gives a demonstration of what would happen in such a scenario:.
public static void Main()
{
    Console.WriteLine("Web Server Started");
    TcpListener listener = new TcpListener(IPAddress.Any,99);
    listener.Start();

    while (true)
    {
        // creates a connection to accept client requests
        Socket conn = listener.AcceptSocket();
    
        Stream stream = new NetworkStream(conn);
        
        StreamWriter sw = new StreamWriter(stream);
        StreamReader sr = new StreamReader(stream);

        // Waits for the user to send a request, typically in the form of a GET Request
        string incoming_data = sr.ReadLine();

        Console.WriteLine(incoming_data);

        stream.Close();
        conn.Close();
    } 
}

This code extends the previous server by continuously accepting connections:

  1. It enters an infinite loop to keep accepting clients.
  2. Inside the loop, it waits for a client to connect and accepts the connection.
  3. It opens communication streams for sending (write) and receiving (read) data.
  4. It reads the incoming data (likely a request) from the client and prints it to the console.
  5. Finally, it closes the connection after receiving the data.

Making a simple web browser:

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;

public static class WebServer
{
    public static void Main()
    {
        string websiteAddress;
        while (true)
        {   
            Console.WriteLine("Enter The website you want to connect with: ");

            // Takes an input from the user
            websiteAddress = Console.ReadLine();

            //Establishes a TCP Client to host the connection
            TcpClient client = new TcpClient(websiteAddress,80);
            NetworkStream stream = client.GetStream();

            //Read an Write Streams for I/O of data
            StreamWriter sw = new StreamWriter(stream);
            StreamReader sr = new StreamReader(stream);

            //Standard GET request Format to signal the server to send it's data
            sw.WriteLine("GET / HTTP/1.1\r\n");
            sw.Flush();

            // Keeps on reading the data until the end.
            string data = sr.ReadLine();
            while (data != null) 
            {
                Console.WriteLine(data);
                data = sr.ReadLine();
            }

            stream.Close();
            client.Close();
        }
    }
}
This code builds a basic web browser that repeatedly fetches content from websites:
  1. It prompts for a website address in a loop.
  2. It connects to the entered address as a client (like web browsers do).
  3. It sends a standard GET request (like saying "Show me your content").
  4. It receives the website's response, line by line, and prints it to the console.
  5. It closes the connection and starts the loop again for a new website.

Comments

Popular posts from this blog

Packet Switching

Single Page Application VS Multi Page Applications

How does the Internet work?