gevent-websocket

0.10.1 · maintenance · verified Sun Apr 12

gevent-websocket is a WebSocket library designed for the gevent networking library, integrating with its `pywsgi` server. It provides features like integration at the socket level or through an abstract interface, and supports RPC and PubSub using WAMP (WebSocket Application Messaging Protocol). The current version is 0.10.1, last released in March 2017, suggesting it is in maintenance mode with infrequent updates.

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic WebSocket echo server using the `WebSocketApplication` and `WebSocketServer` classes. It listens on `ws://localhost:8000/` and echoes any received message back to the client. This is the higher-level API for defining WebSocket applications.

from gevent import pywsgi
from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
from collections import OrderedDict

class EchoApplication(WebSocketApplication):
    def on_open(self):
        print("Connection opened")

    def on_message(self, message):
        # Echo the received message back to the client
        print(f"Received: {message}")
        self.ws.send(message)

    def on_close(self, reason):
        print(f"Connection closed: {reason}")

if __name__ == '__main__':
    print("Starting WebSocket echo server on ws://localhost:8000/")
    server = WebSocketServer(
        ('', 8000),
        Resource(OrderedDict([('/', EchoApplication)]))
    )
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("Server stopped.")

view raw JSON →