Junior
How to open a WebSocket connection?
sobes.tech AI
Answer from AI
To open a WebSocket connection on the client side in Python, you can use the websockets library.
import asyncio
import websockets
async def connect_websocket():
uri = "ws://localhost:8765" # WebSocket server address
async with websockets.connect(uri) as websocket:
print("WebSocket connection opened.")
# You can send and receive messages here
if __name__ == "__main__":
asyncio.run(connect_websocket())
On the server side, also using websockets:
import asyncio
import websockets
async def handle_client(websocket, path):
print(f"Client connected from {websocket.remote_address}")
# You can process messages from the client here
async def start_server():
start_server = websockets.serve(handle_client, "localhost", 8765)
print("WebSocket server started on ws://localhost:8765")
await start_server.serve_forever()
if __name__ == "__main__":
asyncio.run(start_server())
Main steps:
- Import the library:
import websockets. - Specify the address: WebSocket server URI (
ws://...orwss://...). - Create a connection: Use
websockets.connect()on the client orwebsockets.serve()on the server. They are asynchronous functions and are usually used withasync withfor automatic connection closing. - Handle events: After establishing the connection, you can send and receive messages asynchronously.
Alternatives:
websocket-client: Client library not based onasyncio.autobahn|python: Older library supporting both client and server.
The choice depends on project requirements (asynchronous, features, performance). For modern async applications, websockets is recommended.