Simple WebSocket Echo Server with Connection Handling

  • Share this:

Code introduction


This code defines a simple WebSocket server that can echo messages received from clients and perform actions on connection open and close.


Technology Stack : Autobahn, asyncio, websocket

Code Type : WebSocket example

Code Difficulty : Intermediate


                
                    
import asyncio
from autobahn.asyncio import websocket
from autobahn.websocket import ApplicationRunner

def websocket_example():
    async def on_open连接(websocket, request):
        await websocket.send("Hello, World!")
    
    async def on_message(websocket, message):
        await websocket.send(f"Received: {message}")
    
    async def on_close(websocket, was_clean, code, reason):
        print("WebSocket closed")
    
    runner = ApplicationRunner("ws://echo.websocket.org", "/ws")
    await runner.run({
        "autobahn": "0.13.3",
        "websocket": "0.14.3",
        "on_open": on_open,
        "on_message": on_message,
        "on_close": on_close
    })