How To Build WebSocket Server And Client in Python

Hasan Sajedi
3 min readJul 6, 2022

What is WebSocket?

A WebSocket is a client-server connection that remains open throughout time.

Through a single TCP/IP socket connection, WebSockets enable a bidirectional, full-duplex communications channel that functions over HTTP.

Python

Python is an interpreted high-level, general-purpose programming language. The use of considerable indentation in its design philosophy emphasizes code readability. Its language elements and object-oriented approach are aimed at assisting programmers in writing clear, logical code for both small and large-scale projects.

Building a WebSocket Server With Python

Let’s first set up the environment:

  1. Make sure you have python installed in your system.
  2. Now use pip to install the WebSocket package using the command below:

pip install websockets

We can start building the server and a client to connect once you’ve installed the WebSockets package.

Now Let’s create a Server:

Create a server file for example “server.py”.

Inside the server file, we import the required packages — in this case, asyncIO, and WebSockets.

Paste the following code for creating a web server:

import asyncio

import websockets

# create handler for each connection

async def handler(websocket, path):

data = await websocket.recv()

reply = f”Data recieved as: {data}!”

await websocket.send(reply)

start_server = websockets.serve(handler, “localhost”, 8000)

asyncio.get_event_loop().run_until_complete(start_server)

asyncio.get_event_loop().run_forever()

Then we’ll wait for the message and the incoming connection. We take action based on the information we’ve gathered. A basic response containing the contents of the received data in our example.

Let’s create a Client Now:

Create a file and call it client.html. Inside the file, paste the following code:

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”UTF-8">

<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>

<meta name=”viewport” content=”width=device-width, initial-scale=1.0">

<title>WebSocker Client</title>

</head>

<body>

<button onclick=”contactServer”>Click Here</button>

</body>

<script>

const socket = new WebSocket(‘ws://localhost:8000’);

socket.addEventListener(‘open’, function (event) {

socket.send(‘Connection Established’);

});

socket.addEventListener(‘message’, function (event) {

console.log(event.data);

});

const contactServer = () => {

socket.send(“Initialize”);

}

</script>

</html>

Save the file and open it in the browser.

You can see in the console connection is established.

WebSocket Client with Python

Now Let’s create a WebSocket client connection in python.

Create a new File “client.py” and import the packages as we did in our server code.

import asyncio

import websockets

Now let’s create a Python asynchronous function (also called coroutine).

async def test():

We will use the connect function from the WebSockets module to build a WebSocket client connection. It returns a WebSocketClientProtocol object, which may be used to transmit and receive WebSocket messages.

async def test():

async with websockets.connect(‘wss://demo.piesocket.com/v3/channel_1?api_key=YOUR_API_KEY’) as websocket:

To send the data, we simply call the send coroutine with the string of data we wish to send to the client as input. We’ll send a straightforward “hello” message.

Because this is a coroutine, we’ll use the await keyword to wait for it. Note that using await suspends the current coroutine’s execution (in our example, the test function) until the await completes and provides the result data.

await websocket.send(“hello”)

The recv coroutine is then called to receive the data from the client. Let’s see the full code:

import asyncio

import websockets

async def test():

async with websockets.connect(‘wss://demo.piesocket.com/v3/channel_1?api_key=YOUR_API_KEY’) as websocket:

await websocket.send(“hello”)

response = await websocket.recv()

print(response)

asyncio.get_event_loop().run_until_complete(test())

Now run your code you will get “hello” as your output.

Hope this helps you with your journey to build a WebSocket Server & Client in Python.

--

--