Crossbar.io WebSocket Echo Server Implementation

  • Share this:

Code introduction


This code creates a simple WebSocket echo server using Crossbar.io. The server listens for incoming WebSocket connections and echoes back the received messages to the client.


Technology Stack : Python, Crossbar.io, WebSocket

Code Type : Function

Code Difficulty : Intermediate


                
                    
def crossbar_websocket_echo(arg1, arg2):
    """
    This function creates a simple WebSocket echo server using Crossbar.io.
    The server listens for incoming WebSocket connections and echoes back the received messages.
    
    :param arg1: The host address on which the WebSocket server will run.
    :param arg2: The port number on which the WebSocket server will run.
    """
    from crossbar import crossbar
    from crossbar.api import crossbarapi
    from crossbar.api.component import Worker

    class Echo(Worker):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.name = 'echo_worker'
            self.on_message = self.on_message_handler

        async def on_message_handler(self, payload, msg):
            await self.send(msg.source, payload)

    def on_connect(source):
        print(f"Connection from {source}")

    def on_disconnect(source):
        print(f"Disconnection from {source}")

    api = crossbarapi()
    api.add_resource(Echo, '/ws')
    api.on_connect = on_connect
    api.on_disconnect = on_disconnect
    api.start(arg1, arg2)