gevent-websocket
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
- deprecated The library's last release was in March 2017, indicating a low maintenance or potentially abandoned status. Users seeking actively developed WebSocket solutions with gevent might consider alternatives like `gevent-ws` which explicitly states itself as an MIT-licensed alternative to the 'abandoned' gevent-websocket.
- breaking The `wait()` method was renamed to `receive()` in earlier versions (pre-0.10.1). If upgrading from very old versions or referencing outdated documentation, this change can cause `AttributeError`s.
- gotcha When integrating with WSGI applications (especially with `WebSocketHandler`), the WebSocket object is exposed via `environ['wsgi.websocket']`. Applications must explicitly check for the presence of this key to determine if a request is a WebSocket upgrade or a standard HTTP request.
- gotcha When combining `gevent-websocket` with `Flask-SocketIO`, installing `gevent-websocket` can unexpectedly break `Flask-SocketIO`'s WebSocket server functionality, leading to connections immediately closing, even though `Flask-SocketIO` itself might recommend installing it for performance.
Install
-
pip install gevent-websocket
Imports
- WebSocketServer
from geventwebsocket import WebSocketServer
- WebSocketApplication
from geventwebsocket import WebSocketApplication
- Resource
from geventwebsocket import Resource
- WebSocketHandler
from geventwebsocket.handler import WebSocketHandler
- WebSocketError
from geventwebsocket import WebSocketError
Quickstart
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.")