Creating an Autobahn WebSocket Echo Server

  • Share this:

Code introduction


This function creates a WebSocket echo server using the Autobahn library. It can receive messages from clients and send them back as is.


Technology Stack : Autobahn, asyncio

Code Type : The type of code

Code Difficulty :


                
                    
import asyncio
from autobahn.asyncio import websocket

def echo_server():
    """
    This function sets up an asynchronous WebSocket echo server using the Autobahn library.
    """
    # Define the WebSocket echo server
    async def on_open(ws, req):
        print("Client connected")

    async def on_message(ws, message):
        print("Received message: {}".format(message))
        await ws.send(message)

    async def on_close(ws, req):
        print("Client disconnected")

    # Start the WebSocket echo server
    start_server = websocket.WebSocketServerFactory(u"ws://localhost:8080").start_server(
        on_open=on_open,
        on_message=on_message,
        on_close=on_close
    )

    loop = asyncio.get_event_loop()
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        loop.close()