Network Programming
First of all, Network Programming is the field in programming where there are two sides involved. First side is SERVER SIDE and Second side is CLIENT SIDE.
Network Programming is a way of connecting two nodes on a network to communicate with each other. One socket listens on a particular port at an IP, while other socket reaches out to the other to form a connection. Server forms the listener socket while client reaches out to the server
Server is a software/program/application/script which accepts request, process the respective request creates the response and return it to client.
Client is also a software/program/application/script which initiates request and send it to server and receives the response send by server.
Proper Cycle of Network Programming
Client initiates the request and sends it to Operation System, Os sends it to a network and Server Side OS receives the request and send it to Server. Now request is received at server side now server processes the request creates response for the request and sends the response to Operating System and OS sends it to a network and Client side OS receives the response through network and OS send the response to Client Software and thus proper cycle of networking ends.
Steps for creating a Server Script-:
1. Create a Server Socket (server socket is a socket that can accept request)
2. Bind the Server Socket to a port (range of ports is 1–65353)
3. Put the Server Socket in listening mode for accepting request
4. Divert the incoming request of server socket to an additional socket
5. Process the request
6. Create the response (not mandatory)
7. Send the response (not mandatory)
Why is it important to divert the incoming request on server socket to an additional socket ???
It is recommended to divert the incoming request on server socket to an additional socket. The reason behind that is this act should be performed to make server ready to accept next request.
In simple words if server socket will only accept and handle a single request at same time then client have to wait to send other request till the previous request is processed and thus to make 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 request
4. Send request to server through client socket
5. Accept response from server through client socket
Connection with server can established using IP address or if application would be running on 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 server will be able to handle multiple request at same time so it is very much important in network programming that a server should be multi-threaded. Whenever client connects and sends the request, a new thread should form and request should be diverted to additional socket on new thread so that processing for the request should happen on seperate thread and simultaneously server will accept other request and in this way server will handle multiple requests.
Example for network programming
I will create a python script named server.py and client.py to demonstrate networking.
server.py
import socket serverSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #creating socket named as server socket
serverSocket.bind((“localhost”,5500))
#binding the server socket to port number 5500
serverSocket.listen() #putting server in listening mode
print(“Server is ready and listening on port: 5500”)
clientSocket,clientSocketName=serverSocket.accept()
#diverting the incoming request to additional socket
a=clientSocket.recv(100)
a=a.decode(“utf-8”)
a=a.strip()
a=int(a)
b=clientSocket.recv(a) #receiving the request
b=b.decode(“utf-8”)
print(“Request Arrived: “,b)
b+=b[::-1] #creating response
print(“Response: “,b)
c=len(b)
c=str(c).ljust(100)
c=bytes(c,”utf-8")
clientSocket.sendall(c)
b=bytes(b,”utf-8")
clientSocket.sendall(b) #sending response
print(“Response sent”)
clientSocket.close()
client.py
import socket
clientSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.connect((“localhost”,5500))
a=input(“Enter a string: “)
strlen=len(a)
slen=str(strlen).ljust(100)
b=bytes(slen,”utf-8")
clientSocket.sendall(b)
a=bytes(a,”utf-8")
clientSocket.sendall(a)
c=clientSocket.recv(100)
c=c.decode(“utf-8”)
c=c.strip()
c=int(c)
d=clientSocket.recv(c)
d=d.decode(“utf-8”)
print(“Response: “,d)
clientSocket.close()
So in the above image and code you can clearly observe that i entered “Tanishq” as input which was my request and send it to server, at server side processing was done and response was created which was a string made by concatenating request with it reverse form and response was send from server side and was received at client end. This is a simple exam for demonstrating network programming.
I will create a java program named server1.java and client1.java for demonstrating network programming in java
server1.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(“Request Arrived: “+request);
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
client1.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
In this example I gave data for initiating request at client side as command line arguments, Client side initiated the request sends it to server side and server side code saves the data somewhere it can in file, data structure or in database it depends on the user, since it is an example i saved it in variables. and in response server sends a string “Data Saved”.