SOCKET PROGRAMMING – COMPUTER NETWORKS

socket programming

There are always two processes that are communicating with each other. Every process that wants to send a message to other process has to send through the underlying network and underlying networking layers. A process sends and receives a message from the network through a device or a software, called as socket.

Let me give you an example, so you clearly understand what a socket is.
 

Suppose you want to send a message to your friend ( say, James). Here, you are the process. Now, what will you do? You will write a message and put it into an envelope and will go and open the door so that you should give this envelope to the postman who can deliver your envelope to your friend. Here your house door is the socket and the postman and the post-office are the underlying network and the networking layers. In the same way, the network will deliver the envelope to your friend, through his house door. There, your friend is process and the door is socket.

As in real world, setting up a door is very easy. But in computer networking, socket programming is bit complex and needs to be understood well before you could start executing. While developing an Application and writing code for socket programming, the developer must be clear, whether the application has to be run over TCP or UDP. As you know, TCP is connection-oriented and provides a reliable delivery of messages. While UDP is connectionless and provides no guarantee for the delivery of packets.
 
When two processes communicate with each other, they have to read and write messages to the socket. Thus, socket programming is a very crucial task, that an Application developer has to do. Thus in networking world, codes must be written both for client and server programs. These codes can be in any language such as Java, Python, C, C++ etc. It’s up to the Application developer in which language, he has a good understanding. Here I am going to tell you the code in Python. As in Python, it’s really very easy to understand the code. Even a novice can easily understand it, as Python describes each and every concept of Socket programming very deeply. But as I already mentioned, socket programming can be done in any language, so if you don’t have a good hand in Python, then no need to worry, you can write it in some other language also.
 

Now, lets start with the implementation of the code for Socket. We will start with Socket programming for UDP and then will move on to TCP.

i) Socket Programming with UDP

client server communications

 I will demonstrate this using a very simple example. We will use the same scenario for programming with TCP also.
 

1.  The client enters some input through keyboard and sends it to the server.

2.  The server receives the data and converts it into upper case letters.
 

3.  The server delivers the modified data to the client.

4.  The client receives the data and displays it onto its screen.
 
 

Let’s now write a code for UDP socket. Here the client is said to be as UDP client and server is called as UDP server. You are familiar with port number and you know that every application must have a specific port number. In this example, let us suppose port number as 9900.

 

            a) UDP Client

from socket import *

serverName=’hostname’

serverPort= 9900

clientSocket= socket(socket.AF_INET,socket.SOCK_DGRAM)

message=raw_input( ‘ Enter the lower case letters: ‘ )

clientSocket.sendto(message,(serverName,serverPort))

modifiedMessage, serverAddress=clientSocket.recvfrom(1500)

print modifiedMessage

clientSocket.close()

 

Might be you have understood the program by reading it. But let’s describe it line by line and have a look, what every line do in this program.

 

i)       from socket import *

 By writing this line, we will be able to create sockets within our programs.
 

ii)       serverName=’hostname’

          serverPort = 9900

 The 1st line will set the string serverName to the hostname. It can either contain the hostname of the server (for example: fitnytech.com) or the IP address of the server(187.45.123.34). If the hostname of the server is used, then automatically DNS lookup will be performed, to find the IP address of the server. The 2nd line will give the server port number as 9900.
  

iii)        clientSocket= socket(socket.AF_INET,socket.SOCK_DGRAM)

This creates the client’s socket as clientSocket. The parameters indicate the family address. AF_INET indicates that the underlying protocol is IPv4. And SOCK_DGRAM indicates that it is a UDP socket.
 

iv)         message=raw_input( ‘ Enter the lower case letters: ‘ )

There is a built-in function raw_input in Python. When this command is executed, the client prompted with a line, Enter the lower case letters. The user will input the data, that will be put into a message
 

Now the data is ready and the socket is ready. We should now send the data. 

v)          clientSocket.sendto(message,(serverName,serverPort))

Here the sendto function will bind the serverName and the serverPort with the message and will send it into the socket. 
 

vi)          modifiedMessage, serverAddress=clientSocket.recvfrom(1500)

 When the response will come at the client socket, it will be stored in the variable modifiedmessage. The source address of the packet is stored in variable serverAddress. The serverAddress contains both the server IP address and server port number. 
  

vii)          print modifiedMessage

 This command will print the message onto the client screen.
  

viii)          clientSocket.close()

 This will stop the client socket. the program will terminate. 
 
 

            b) UDP Server

 

from socket import *

serverPort = 9900

serverSocket = socket(AF_INET,SOCK_DGRAM)

serverSocket.bind( ‘ ‘ , serverPort)

print “Server is on”

while 1:

message, clientAddress = serverSocket.recvfrom(1500)

modifiedMessage = message.upper()

serverSocket.sendto(modifiedMessage,clientAddress)

 
 Now let’s go through it line by line. You can see the 1st three lines are same as the client. We will move on forward.
 
 

i)         serverSocket.bind( ‘ ‘ , serverPort)

This command will bind the socket with the server port number. After this, the server will enter a while loop, that will enable the server to process a client request more than once.
  

ii)       message, clientAddress = serverSocket.recvfrom(1500) 

The incoming message from the client will be put in the variable message. The message source address will be stored in the variable clientAddress. The clientAddress will contain the IP address of the client and the source port number. The server uses these 2 informations, in order to reply the query to the appropriate client at its respective port. 
 

iii)       modifiedMessage = message.upper()

This will process the request from the user at client side and will capitalise the words in the message.
 
 

iv)       serverSocket.sendto(modifiedMessage,clientAddress)

This line will send the modified message to the client. 
 
 

Now you should implement socket programming on your system. Just install and compile a UDP client on one host and UDP server on another host. But don’t forget to give the port number, the IP address properly to both the hosts. 

You can develop your own UDP client-server Application.  For example: Here I have taken an example of converting from lower case to upper case. You can modify it by counting the number of words you have typed, or count the appearance of a word in the line. In this way, you can develop any UDP client-server Application on your own systems.
  

ii) Socket Programming with TCP

client server handshake TCP

As you already know, that TCP is a connection oriented protocol. Thus before really transmitting the data, the two communicating hosts have to set up a dedicated connection between them. This is called a 3-way handshake. 
 

To set-up a new connection, the clients knocks on the Welcoming socket of the server. After hearing the request from the client, the server allocates a new Connection socket to that particular client, through which the client can send and receive data. 

*****Don’t mix Welcoming Socket with Connection Socket. These are two different Sockets.*****
 
 

Let us explain it, by drawing a figure for you.

 

Socket programming in computer networks, welcoming socket in server, connection socket of server, client socket requesting server, 3-way handshake in transport layer

 

            a) TCP Client

from socket import *

serverName= ‘servername’

serverPort=9900

clientSocket=socket(AF_INET , SOCK_STREAM)

clientSocket.connect((serverName,serverPort))

sentence=raw_input( ‘Enter the letters’ )

clientSocket.send(sentence)

modifiedSentence = clientSocket.recv(1500)

print ‘From Server:’, modified Sentence

clientSocket.close()

i)        clientSocket = socket(AF_INET, SOCK_STREAM)

This line creates a client’s socket, clientSocket. AF_INET tells about the underlying layer protocol i.e. IPv4. SOCK_STREAM indicates that it is a socket for TCP.

ii)       clientSocket.connect((serverName,serverPort))

As you know, that a client has to initiate a connection with the server, before the actual transfer of data begins. This line establishes a connection between server and client. After this line, the 3-way handshake is performed between server and client.

iii)      sentence=raw_input( ‘Enter the letters’ )

This line will ask the client to enter the text.

iv)       clientSocket.send(sentence)

This line sends the message into the client socket and into the TCP connection. You must have noticed a difference here. In UDP client, the port number has to define, but here it is not needed, as there is already a handshake between client and server. 

v)        modifiedSentence = clientSocket.recv(1500)

When the modified sentence comes from the server, it is accumulated in modifiedSentence. And then the client retrieves it on its screen.

vi)        print ‘From Server:’, modified Sentence

This line is used to print the modified sentence onto the client screen.

vii)      clientSocket.close()

This line closes the connection. The process terminates.

 

            b) TCP Server

from socket import *

serverPort = 9900

serverSocket = socket(AF_INET , SOCK_STREAM)

serverSocket.bind(( ‘ ‘ , serverPort))

serverSocket.listen(1)

print ‘The server is ready to receive’

while 1:

connectionSocket, addr = serverSocket.accept()

sentence = connectionSocket.recv(1500)

capitalizedSentence = sentence.upper()

connectionSocket.send(capitalizedSentence)

connectionSocket.close()

i)                 serverSocket.bind(( ‘ ‘ , serverPort))

This line attaches the socket with the port number.

ii)                serverSocket.listen(1)

This line indicates about the server for listening request from the client. The parameter 1 symbolizes, that atleast 1 client should be there.  Here the server socket is the welcoming socket.

iii)                 connectionSocket, addr = serverSocket.accept() 

When a client requests at the socket or knocks at the server door, the program invokes a accept() method for the serverSocket, that invokes a new socket for the server, that is Connection Socket, dedicated to a particular client. Now after establishing a TCP connection, client and server can exchange files. 

iv)                 sentence = connectionSocket.recv(1500)

                    capitalizedSentence = sentence.upper()

                    connectionSocket.send(capitalizedSentence)

                    connectionSocket.close()

You can easily understand the functioning of these 4 lines by reading them only. Finally, when the server, sends the Capitalised words to the client and the request of the client is processed, it closes the connection. And the process terminates.

Thank You for reading this article. We hope you enjoyed it.
 
This information can be useful for someone in your circle. Share with them on Facebook, Google+, Linkedin.
Raman Deep Singh Chawla

Raman Deep Singh Chawla

Raman is the founder of FitnyTech . He is a fitness App Developer and a Blogger. He is fond of his fitness and sports. He has great passion for Cricket , Tennis , Soccer and Table Tennis. In his free time , he loves to learn about technology , write about it , share his thoughts with others. His passion for technology can be seen at his blogs.

More Posts

Leave a Reply

Your email address will not be published. Required fields are marked *