Autobahn WebSocket Server Echo Example

  • Share this:

Code introduction


This code defines a WebSocket server using the Autobahn library. The server listens on port 8080 of the local machine, accepts connections and messages from clients, and echoes received messages back to the clients.


Technology Stack : Autobahn, Twisted

Code Type : WebSocket Server

Code Difficulty : Intermediate


                
                    
import asyncio
from autobahn.twisted import protocol
from autobahn.twisted import websocket

class EchoProtocol(websocket.WebSocketServerProtocol):
    def on_open(self):
        print("WebSocket connection opened.")

    def on_message(self, payload):
        print("Received message:", payload)
        self.send_message(payload)

    def on_close(self):
        print("WebSocket connection closed.")

def start_websocket_server():
    from twisted.internet import reactor
    factory = websocket.WebSocketServerFactory("ws://localhost:8080")
    factory.protocol = EchoProtocol
    reactor.listenTCP(8080, factory)
    reactor.run()