Introduction to Websockets library in python

websockets

Ever wondered how your favorite chat applications stay connected? Or how you receive instant notifications on your smartphone? Enter the world of WebSockets. In an era of uninterrupted connectivity and real-time information flow, understanding WebSockets can give you a competitive edge.

In this article, we will introduce WebSockets and how to develop a simple WebSocket connection using websockets python library. It is an application layer protocol that allows two-way communication between a client and a server. WebSockets were invented by developers to effectively facilitate real-time results.

Implementing WebSockets in Python

Let’s get started with creating a websocket to understand the concept better.

1. Setting Up Your Environment

We will start by installing the Websocket library

pip install websockets

Using a virtual environment is recommended while working with several python libraries. Learn how to set up a virtual environment here.

2. Creating a server

Now, the server is the system or program which acts as a host of our application, this can be any application you might be using in your day-to-day life.

The server generally gets the requests for connections from the client and processes the request accordingly. Create a file server.py in your system. We will try to make a small server here. We will start by importing the libraries asyncio and websockets.

import asyncio
import websockets

asyncio is a python library used to write parallel/concurrent code in async/await syntax and websockets is a python library for building WebSocket servers and clients in python.

async def response(websocket, path):
	message = await websocket.recv()
	print(f"We got the message from the client: {message}")
	await websocket.send("I can confirm I got your message!")

Next, we will write our async function response(), It will contain our server code, and it takes our websocket server as a parameter and the path. After that, we will assign a variable message = await websocket.recv() , means that the server awaits a response from the client, and once we get the message the server will move forward. We will print the message received in our console using the print statement in the next line. After that, we will send a confirmation message to the client(Just like we get a double tick in Whatsapp/chat applications) that our message was received.

start_server = websockets.serve(response, 'localhost', 1234)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Now we will add the last few lines coming outside the function of the server. we will define our localhost where our server will run, which I have used localhost:1234 here. The client program will identify our server by this local host. After that, we have used the asyncio library functions to start our server. Learn more about the asyncio library here.

3. Crafting a Client

Now, let’s write a program for our client, which is the user in most of the cases. Create a client.py file in your system and get started.

import asyncio
import websockets

We will start by importing our libraries to write asynchronous functions and establishing the websocket connection.

async def message():
	async with websockets.connect("ws://localhost:1234") as socket:
		msg = input("Write your message to the server: ")
		await socket.send(msg)
		print(await socket.recv())

Next, we will define our client function message(). In the next line, we have established our socket connection using websockets.connect() and note that we have written the address of our server i.e. localhost:1234. After that, we have given an input command to input the message that will be sent to our server.

await socket.send(msg) sends the message to the server via the socket connection established and print(await socket.recv()) will print any updates or messages sent to the client by the server after that.

asyncio.get_event_loop().run_until_complete(message())

Next, we will close our connection after the message is sent(See the outputs in the next section). You can also use the function get_event_loop().run_forever() to run the client for more than one message until u close the console.

4. Running Your Application: The Moment of Truth

Now running the application is pretty straightforward. We will start by running our file server.py

Screenshot 2023 05 28 111913
Server.py running

We have our server running now. Now we will run our client.py file and send a sample message to the server

Screenshot 2023 05 28 112602
Client.py

You can note that we got a confirmation from the server about the message received and the connection was closed (The python program stopped running) after the message. And finally, we will view our message on our server.

Screenshot 2023 05 28 112617
Message received at the server

Always ensure you run the server before the client. If you don’t, the client won’t be able to establish a connection and the program will throw errors.

Wrapping Up: The Power of WebSockets

Today, we’ve scratched the surface of building WebSocket connections using Python. Complex, real-time applications like gaming systems, notification engines, and chat apps use this same technology. How will you leverage the power of WebSockets in your next Python project?