WebSocket is a communication protocol that provides full-duplex communication channels over a single TCP connection. It is often used for real-time web applications such as chat applications, online gaming, and live data streaming. Python has several libraries and frameworks for working with WebSockets. One of the most popular libraries for WebSocket programming in Python is websockets
.
Here’s a basic example of how to use the websockets
library to create a WebSocket server and client in Python:
WebSocket Server:
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)
start_server = websockets.serve(echo, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
In this example, we create a simple WebSocket server that listens on localhost
on port 8765
and echoes back any messages it receives.
WebSocket 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())
In this example, we create a WebSocket client that connects to the WebSocket server we created earlier and sends a message. It then waits for a response from the server and prints it.
Make sure you have the websockets
library installed. You can install it using pip:
pip install websockets
This is a very basic example, and you can extend it to handle more complex communication and implement your desired functionality using WebSockets. WebSocket programming can be more complex when dealing with real-world applications, such as handling multiple clients and managing different types of messages, but this example should give you a good starting point.