Autobahn Python

25.12.2 · active · verified Thu Apr 09

Autobahn Python is a networking library that provides open-source implementations of the WebSocket Protocol and the Web Application Messaging Protocol (WAMP). It allows developers to create high-performance, asynchronous WebSocket clients and servers, and WAMP clients and application components, running on either Twisted or asyncio event loops. Currently at version 25.12.2, the project maintains an active development pace with frequent nightly and development builds, alongside regular stable releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic WebSocket echo server using the `asyncio` backend. It listens on `ws://127.0.0.1:9000` and echoes back any message it receives. This example can be run directly. For WAMP applications, a separate WAMP Router like Crossbar.io is required.

import asyncio
from autobahn.asyncio.websocket import WebSocketServerFactory, WebSocketServerProtocol

class MyServerProtocol(WebSocketServerProtocol):
    def onConnect(self, request):
        print(f"Client connecting: {request.peer}")

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print(f"Binary message received: {len(payload)} bytes")
        else:
            print(f"Text message received: {payload.decode('utf8')}")

        # echo back message verbatim
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print(f"WebSocket connection closed: {reason} (code={code}, clean={wasClean})")

async def main():
    factory = WebSocketServerFactory("ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol

    server = await asyncio.get_event_loop().create_server(factory, '127.0.0.1', 9000)
    print("WebSocket server started on ws://127.0.0.1:9000")

    try:
        await server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        await server.wait_closed()
        asyncio.get_event_loop().close()

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →