Introduction to Network Programming (Socket Programming)

Tanishq Rawat
5 min readApr 2, 2022

--

Introduction

If you want to make two systems communicate then the communication mechanism between two systems using TCP, can be established using Sockets and is known as Socket Programming (Network Programming). It is the implementation of the TCP-IP protocol. Hence, Socket Programming is a concept of Network Programming, that suggests writing programs that are executed across multiple systems, which are connected to each other using a network.

What are Sockets?

A socket is a software object that acts as an endpoint establishing a bidirectional network communication link between a server-side and a client-side program.

Every socket is bound to a port that is available at the operating system level, the range of ports is 0–65536, where 0–1024 serial number ports are reserved for operating system functions, we can use them too but that can affect any background process and can lead to crashing. So ideally we should use the port number from 1025 to 65536.

What is server and client?

The Server is a software/program/application/script which accepts the request, processes the respective request creates the response, and returns it to the client.

The Client is also a software/program/application/script which initiates a request and sends it to the server and receives the response sent by the server.

Proper Cycle of Network Programming

A client initiates the request and sends it to Operation System, Os sends it to a network using NIC, and Server Side OS receives the request and sends it to Server. Now the request is received at the server-side now server processes the request creates a response for the request and sends the response to Operating System and OS sends it to a network using NIC and Client-side OS receives the response through the network and OS sends the response to the Client Software and thus the proper cycle of networking ends.

Steps for creating a Server Script-:
1. Create a Server Socket (server socket is a socket that can accept requests)
2. Bind the Server Socket to an IP + port number(range of ports is 0–65536)
3. Put the Server Socket in listening mode for accepting the request
4. Divert the incoming request of the server socket to an additional socket
5. Process the request
6. Create the response (not mandatory)
7. Send the response (not mandatory)

NOTE-: Any system can have multiple IP addresses if and only if it has multiple network interface cards configured in the hardware.

Why is it important to divert the incoming request on the server socket to an additional socket ???

It is recommended to divert the incoming request on the server socket to an additional socket. The reason behind that is that this act should be performed to make the server ready to accept the next request.
In simple words if the server socket will only accept and handle a single request at the same time then the client has to wait to send another request till the previous request is processed and thus making the server socket free and ready to accept another request it is recommended to divert incoming request on server socket to an additional socket.

Note for Server-Side Script-: We should never use Ports between 1–1024 since these ports are system ports, still we can use them but it can affect the system processes so we should avoid using this range of ports for binding our socket to the port.

Steps for creating Client Script-:
1. Create a client socket
2. Connect client socket to server socket
3. Create a request
4. Send a request to the server through the client socket
5. Accept the response from the server through the client socket

Connection with the server can be established using an IP address or if the application would be running on the same system then we can directly specify the port number.

Why Server should be multi-threaded?

A big and important question that why a server should be multi-threaded. As there can be more than 1 client then how the server will be able to handle multiple requests at the same time it is very much important in network programming that a server should be multi-threaded. Whenever a client connects and sends the request, a new thread should form, and the request should be diverted to the additional socket on the new thread so that processing for the request should happen on a separate thread and simultaneously server will accept other requests and in this way server will handle multiple requests.

Demonstration

Demonstrating socket programming in C/C++

The server-side script [C language].

//Server.c
#include<stdio.h>
#include<string.h>
#include<windows.h>
#include<unistd.h>
int main()
{
char response[5000];
char request[5000];
int serverSocketDescriptor;
int clientSocketDescriptor;
struct sockaddr_in serverSocketInformation;
struct sockaddr_in clientSocketInformation;
int successCode;
int len;
WORD ver;
WSADATA wsaData;
ver=MAKEWORD(1,1);
WSAStartup(ver,&wsaData);
serverSocketDescriptor=socket(AF_INET,SOCK_STREAM,0);
if(serverSocketDescriptor<0)
{
printf("Unable to create socket\n");
return 0;
}
serverSocketInformation.sin_family=AF_INET;
serverSocketInformation.sin_port=htons(7070);
serverSocketInformation.sin_addr.s_addr=htonl(INADDR_ANY);
successCode=bind(serverSocketDescriptor,(struct sockaddr *)&serverSocketInformation,sizeof(serverSocketInformation));
if(successCode<0)
{
printf("Unable to bind socket at port: 7070\n");
return 0;
}
listen(serverSocketDescriptor,10);
printf("Tanishq's Server is ready to accept request(s) on port 7070\n");
len=sizeof(clientSocketInformation);
clientSocketDescriptor=accept(serverSocketDescriptor,(struct sockaddr *)&clientSocketInformation,&len);
if(clientSocketDescriptor<0)
{
printf("Unable to accept client connection\n");
close(serverSocketDescriptor);
return 0;
}
successCode=recv(clientSocketDescriptor,request,sizeof(request),0);
if(successCode>0)
{
printf("Request: %s\n",request);
}
strcpy(response,"Hello this is Tanishq, How are you");
successCode=send(clientSocketDescriptor,response,strlen(response)+1,0);
if(successCode>0)
{
printf("Request Sent\n");
}
else
{
printf("unable to send Request\n");
}
WSACleanup();
closesocket(clientSocketDescriptor);
closesocket(serverSocketDescriptor);
return 0;
}

The client-side script [C language].

#include<stdio.h>
#include<string.h>
#include<windows.h>
int main()
{
int clientSocketDescriptor;
int serverSocketDescriptor;
struct sockaddr_in serverSocketInformation;
char request[5000];
char response[5000];
WORD ver;
WSADATA wsaData;
ver=MAKEWORD(1,1);
WSAStartup(ver,&wsaData);
clientSocketDescriptor=socket(AF_INET,SOCK_STREAM,0);
serverSocketInformation.sin_family=AF_INET;
serverSocketInformation.sin_port=htons(7070);
serverSocketInformation.sin_addr.s_addr=inet_addr("127.0.0.1");
connect(clientSocketDescriptor,(struct sockaddr *)&serverSocketInformation,sizeof(serverSocketInformation));
strcpy(request,"Hello Tanishq, I am a programmer");
send(clientSocketDescriptor,request,strlen(request)+1,0);
recv(clientSocketDescriptor,response,sizeof(response),0);
printf("Response: %s",response);
closesocket(clientSocketDescriptor);
return 0;
}

Video demonstration of runtime for C language.

Demonstrating socket programming in Java

The server-side script [Java].

import java.io.*;
import java.net.*;
class Server1
{
private ServerSocket serverSocket;
private Socket socket;
Server1()
{
try
{
serverSocket=new ServerSocket(5500);
startListening();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}//constructor ends
private void startListening()
{
try
{
InputStream is;
InputStreamReader isr;
OutputStream os;
OutputStreamWriter osw;
StringBuffer sb;
int x;
int c1,c2;
String pc1,pc2,pc3;
int rollNumber;
String name;
String gender;
String request,response;
while(true)
{
System.out.println("Server is ready to accept request on port 5500\n");
socket=serverSocket.accept();//ServerSocket will go in wait mode here
is=socket.getInputStream();
isr=new InputStreamReader(is);
sb=new StringBuffer();
while(true)
{
x=isr.read();
if(x==-1) break;
if(x=='#') break;
sb.append((char)x);
}
request=sb.toString();
System.out.println("Data Saved");
c1=request.indexOf(",");
c2=request.indexOf(",",c1+1);
pc1=request.substring(0,c1);
pc2=request.substring(c1+1,c2);
pc3=request.substring(c2+1);
rollNumber=Integer.parseInt(pc1);
name=pc2;
gender=pc3;
System.out.printf("Roll Number: %d\nName: %s\nGender: %s\n\n",rollNumber,name,gender);
response="Data Saved#";
os=socket.getOutputStream();
osw=new OutputStreamWriter(os);
osw.write(response);
osw.flush();
socket.close();
}
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public static void main(String gg[])
{
Server1 server=new Server1();
}
}//class ends

The client-side script [Java].

import java.net.*;
import java.io.*;
class Client1
{
public static void main(String gg[])
{
try
{
int rollNumber=Integer.parseInt(gg[0]);
String name=gg[1];
String gender=gg[2];
String request=rollNumber+","+name+","+gender+"#";
String response;
Socket socket=new Socket("localhost",5500);
OutputStream os;
OutputStreamWriter osw;
InputStream is;
InputStreamReader isr;
StringBuffer sb;
os=socket.getOutputStream();
osw=new OutputStreamWriter(os);
osw.write(request);
osw.flush();
is=socket.getInputStream();
isr=new InputStreamReader(is);
sb=new StringBuffer();
int x;
while(true)
{
x=isr.read();
if(x==-1)break;
if(x=='#')break;
sb.append((char) x);
}
response=sb.toString();
System.out.println("Response is: "+response);
socket.close();
}catch(Exception e)
{
System.out.println(e);
}
}//main ends
}//class ends

Demonstrating socket programming in Python

The server-side script [Python].

import socket
serverSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.bind(("localhost",5500))
serverSocket.listen()
print("Server is ready and listening on port: 5500")
clientSocket,clientSocketName=serverSocket.accept()
print("Request Arrived")
#print(clientSocket)
#print(clientSocketName)
request=""
while True:
a=clientSocket.recv(1)
b=a.decode(encoding="utf-8")
if b=="#": break
request+=b
print("Request: ",request)
clientSocket.sendall(b'Got it#')
clientSocket.close()

The client-side script [Python].

import socket
clientSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.connect(("localhost",5500))
#print(clientSocket)
clientSocket.sendall(b'101,Tanishq Rawat,Male#')
print("Request sent")
response=""
while True:
a=clientSocket.recv(1)
b=a.decode(encoding="utf-8")
if b=="#": break
response+=b
print("Response arrived: ",response)
clientSocket.close()

--

--

Tanishq Rawat
Tanishq Rawat

Written by Tanishq Rawat

SDE @ Mobileum | Ex-SDE Intern at Cerebry

No responses yet