How To Use Python Socket Programming For Computer Networking?

How To Use Python Socket Programming For Computer Networking?

In today’s digitalized world, the internet has become a part and parcel of our existence. And, needless to say, “networks” and “connections” play a vital role in the functioning of the internet. To create networks and connections, you need sockets. Sockets are the endpoints existing in a two-way communication link that connects two programs running on a network. The client socket and the server socket are the fundamental aspects that drive web browsing.

As such, socket programming is one of the basic technologies that drive computer networking. This post speaks about the importance of Python socket programming and provides you much-needed guidance on how to implement it.

What is socket programming?

Sockets and socket APIs offer a type of IPC (inter-process communication) that facilitates sending messages across a network. This network can be a local computer network. Also, the network can be physically connected to an external network, while being connected with other networks. A good example is the internet that you can connect through your ISP. 

Developers use socket programming for establishing a connection link between a client’s socket and the server socket. The communication between these two sockets happens bi-directionally and in real time. And, since direct socket connections allow you to send or receive data anytime, it can be immensely beneficial for real-time apps.

This is how socket programming connects two nodes on a network and enables them to communicate with each other. One node (socket) listens on a specific port at an IP. The other node reaches out to the other forming a connection. The server socket is the listener socket and the client socket reaches out to the server socket.

Why use Python for socket programming?

For carrying out the communication between the server and the client you need to write to or read from their sockets. Python’s standard library provides a simple and easy-to-use socket interface. Using the socket module of Python, you can access the BSD socket interface. This module is available on all the modernized versions of Windows, Unix systems, Mac OSX, OS/2, BeOS, and more. Take a look at the reasons why Python is a popular pick for socket programming.

As Python’s socket API is easy to understand, it becomes effortless to write socket programs. The socket programs written in Python, run on various OSs because of Python’s cross-platform compatibility. Moreover, there are a wide variety of third-party libraries available. This proves handy when you need to develop complex socket-based apps.

Python’s socket library offers an in-built support for the TCP/IP protocol which is widely used for network communication. Furthermore, there’s a huge and dynamic developer community that extends help through documentation, tutorials, and support to those working on socket programming in Python.

Python Socket Programming: Client-to-Server Communication

How To Use Python Socket Programming For Computer Networking?

How to set up the Environment?

This is how you need to set up the environment for Socket programming in Python for establishing communication between two computers in the same network.

Make sure that Python is installed on both computers. You can download and install the latest version of Python from the official website. Now, determine the IP addresses of both computers. You can do this by opening the command prompt (on Windows) or terminal (on Linux/Mac) and typing the command ipconfig (on Windows) or ifconfig (on Linux/Mac). Look for the IPv4 address of each computer.

Choose one computer to be the server and the other to be the client. The server will listen for incoming connections, and the client will initiate the connection.

How to establish communication between two computers (Client & Server) in the same network?

Python comes with an in-built library for socket programming – socket. This Python socket library facilitates the communication of Python programs with other devices over a network using different protocols using UDP and TCP.

Here are the steps to follow for communicating with another computer in the same networkusing socket programming in Python:

Use the socket module to create a socket object like UDP or TCP based on yourrequirements. Bind the socket to a particular address and port on your computer employing the bind() method. However, if you just need to connect to another computer, this step is optional for you. Then, listen for incoming connections using the listen() method, if you’re creating a server.And, use the accept() method for accepting the incoming connections coming to the server from the client. Thereafter, connect the client to the server using the connect() method.

Now, send data to the other computer using the send() method and receive data using the recv() method. Once, you’ve finished communicating, close the socket employing the close() method.

Now, take a look at an example of creating a server and a client that communicate with each other using sockets.
Write the server code. The server code should create a socket, bind it to an IP address and port, and listen for incoming connections. The server then accepts the connection, reads the data from the client, and sends it back.

import socket

# create a socket object

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# get local machine name

host = socket.gethostname()

port = 9999

# bind socket to public host, and a port

serversocket.bind((host, port))

# become a server socket


while True:

# establish a connection

clientsocket, addr = serversocket.accept()

print(‘Got a connection from %s’ % str(addr))

#senda “thank you” message to theclient.

message = Thank you for connecting + ‘\r\n’


# close the client connection

Now, write the client code. The client code should create a socket, connect it to the IP address and port of the server, send data through a message, and wait for a response. This is an example of how to create the client code:

import socket

# create a socket object

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# get local machine name

host = socket.gethostname()

port = 9999

# connection to hostname on the port.

clientsocket.connect((host, port))

# receive “welcome message” from server.

message = clientsocket.recv(1024)


print (message.decode('ascii'))

In the aforementioned example, the server listens on port 9999 and waits for incoming connections from clients. The client connects to the server on the same port and gets a ‘welcome’ message from the server. For this, you need to run the server code on the server computer and the client code on the client computer. If everything is set up correctly, the client should establish a connection with the server and send the message "Hello, server!". The server should receive the message and print "Connection from ('client IP address', 'client port') has been established."

In this example, we’ve used TCP sockets and so, used the command socket.SOCK_STREAM. But, if you use UDP sockets instead of TCP sockets, you’ll have to replace the aforementioned command with socket.SOCK_DGRAM. Also, do not forget to close the sockets after you’re done; use the with statement for this. You can also manually call s.close() at the end of your program.

In a nutshell, a server employs the bind() methodology for binding itself to a particular IP and port. This enables the server to listen to incoming requests received on that IP and port. The listen() method turns on the listening mode for the server so that it can listen to incoming connection requests. Then the methods of accept() and close() are used. The accept() method is used to initiate a connection with the client while the close() method closes this connection established with the client.

How to test the output?

For viewing the output, run the socket server program first. After that, you need to run the socket client program. Now, from the client program, write something and then, reply to it from the server program. In the end, write “bye” from the client program for terminating both programs. This is how you can test the output.

Python Socket Programming: Client-to-Client Communication

We have learned how to exchange messages between a client and a server. Now, we will discuss how to establish a connection between two Python clients without involving a server.

Client-to-Client Python-based socket programming, also known as peer-to-peer (P2P) communication, involves establishing a direct communication link between two clients without the need for a central server. There are two methods forsetting up a P2P communication using Python sockets.

The first method is applicable to simple requirements.Itis similar to the steps discussed inthe client-server communication. There’s only a minor modification. You need to select one client to act as the server and the other to behave as the client. The server client will listen for incoming connections, and the client will initiate the connection.

Client-to-Client Communication using PubNub

The client-to-client communication process becomes tricky as the number of devices involved increases. You need to consider aspects like scaling requirements and security. In such a scenario, you can use PubNub, a real-time messaging and communication platform that provides APIs and SDKs for developing real-time applications. This platform is a great choice for client-to-client socket programming in Python, especially for real-time applications that require high scalability and security.

Reasons to use PubNub

PubNub provides easy-to-use APIs and SDKs for multiple programming languages, including Python, which makes it easy to integrate into applications. PubNubcomes with cross-platform support. It supports several platforms including web, mobile, and IoT devices. Hence, it becomes easy to build applications that work across different devices.

PubNub's platform is optimized for real-time communication, which means that messages are delivered quickly and reliably. The platform can handle a large number of connections and messages, making it easy to scale applications as needed. Besides, there are multiple security features, such as end-to-end encryption, access controls, and firewalls, to ensure that messages are secure.

PubNub provides analytics and reporting tools that help developers understand how their application is performing and how users are interacting with it.

Steps to use PubNub for Client-to-Client Communication

With these steps, you can use PubNub for client-to-client socket programming in Python.


Install the PubNub Python SDK employing pip. Pip is the package manager for Python. Then run this command on your command prompt or terminal.

pip install pubnubTop of Form


Now, you need to set up your PubNub account. If you don’t have an account already, youneed to sign up for a PubNub account. Then, create a new PubNub app and obtainyour publish and subscribe keys.


Initialize a new PubNub client in your Python codewith your“publish” and “subscribe” keys. Check out this example:

from pubnub import PubNub

pubnub = PubNub(publish_key='YOUR_PUBLISH_KEY', subscribe_key='YOUR_SUBSCRIBE_KEY')

Subscribe to a channel for receiving messages, after you have initialized the client. This is an example:

def callback(message, channel):

print('Received message:', message)

def error_callback(error):

print('PubNub error:', error)

pubnub.subscribe().channels('my_channel').execute(callback=callback, error=error_callback)

The aforesaid code subscribes to a channel called "my_channel" and sets up a callback function for handling the received messages. The error_callback function gets called if there's an error with the subscription.


To send messages between clients, you can use the “publish” method of the PubNub client. Here's an example:

message = {'text': 'Hello, world!'}

pubnub.publish().channel('my_channel').message(message).pn_async(lambda result, status: print(result, status))

This code publishes a message to the channel called "my_channel" with the text "Hello, world!". The pn_async method establishes a callback function. This function serves the purpose of handling the ‘publish’ operation’s result.

Final Words:

I hope the steps mentioned in this post will help you to correctly execute socket programming using Python whether you wish to establish client-to-server connections or client-to-client connections. Socket programming will become a breeze if these steps are implemented properly and carefully. You may seek technical assistance from a Software Development Services Company in case you are a novice in this arena.
Next Post »