Getting Started with WebSocket in Python

WebSocket is a protocol that enables two-way communication between a server and a client over a continuous connection. In this article, we will begin by getting acquainted with WebSocket in Python.

Installing WebSocket Library

Firstly, you need to install the appropriate WebSocket library. Some popular libraries include websockets, websocket-client, and autobahn.

pip install websockets

Creating a Simple WebSocket Server

Let's start by creating a simple WebSocket server. Below is an example using the websockets library:

import asyncio
import websockets

async def handle_client(websocket, path):
    async for message in websocket:
        await websocket.send("You said: " + message)

start_server = websockets.serve(handle_client, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Establishing WebSocket Connection from Client

Once the server is set up, you can establish a WebSocket connection from the client:

import asyncio
import websockets

async def hello():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello, WebSocket!")
        response = await websocket.recv()
        print(response)

asyncio.get_event_loop().run_until_complete(hello())

By following these simple steps, you've taken a step further in getting acquainted with WebSocket in Python. Continue exploring and building exciting applications using this powerful protocol!