New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

Working with TCP Sockets

As of now, you guys must be familiar with the socket methods described in the previous tutorial. Now we will use those methods in a simple Client-Server Program.

Simple Server Program


#This is script

import socket			                #line 1: Import socket module

s = socket.socket()		                #line 2: create a socket object
host = socket.gethostname()	            #line 3: Get current machine name
port = 9999			                    #line 4: Get port number for connection

s.bind((host,port))		                #line 5: bind with the address

print "Waiting for connection..."	
s.listen(5)			                    #line 6: listen for connections

while True:
	conn,addr = s.accept()	            #line 7: connect and accept from client
	print 'Got Connection from', addr
	conn.send('Server Saying Hi')
	conn.close()		                #line 8: Close the connection

This script will do nothing as of now. It waits for a client to connect at the port specified. If we run this script now, without having a client, it will wait for the connection,

Simple Server Program waiting for client socket

Similarly, every website you visit has a server on which it is hosted, which is always waiting for clients to connect. Now let's create a program and try to connect with our

Simple Client Program

Below is the program. The client tries to connect to server's port, 9999(well defined port). The code line, s.connect((host, port)) opens up a TCP connection to the hostname on the port 9999.


#This is script

import socket			

s = socket.socket()		
host = socket.gethostname()	        # Get current machine name
port = 9999			                # Client wants to connect to server's
				                    # port number 9999
print s.recv(1024)		            # 1024 is bufsize or max amount 
				                    # of data to be received at once

Now, run the script first(if you haven’t yet) and then run the script. If everything goes well, you will see the output as follows:

Simple client Server Program using socket programming in python

Note: Here we are running both client and server on the same machine but a real life scenario is surely different from this, but is similar.

Notice that after executing, terminates but is still running. This is what happens in real scenario too. After fulfiling your request, the Studytonight server keeps on running 24*7 to serve other users.

After executing, server says: Got Connection from ('192.168.43,217', 43402). Here port 43402 is random or ephemeral port assigned to the client by the operating system.

Flow Diagram of the Program

flow diagram for Simple client Server Program using socket programming