pip install gunicorn gevent-websocket
python
# app.py
from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
class MyWebSocketApplication(WebSocketApplication):
def on_open(self):
print("WebSocket connection opened.")
def on_message(self, message):
self.ws.send("You said: " + message)
def on_close(self, reason):
print("WebSocket connection closed.")
if __name__ == "__main__":
WebSocketServer(("127.0.0.1", 8000), Resource({"^/websocket$": MyWebSocketApplication})).serve_forever()
python
# gunicorn.conf.py
workers = 1
worker_class = "geventwebsocket.gunicorn.workers.GeventWebSocketWorker"
bind = "127.0.0.1:8000"
gunicorn -c gunicorn.conf.py app:MyWebSocketApplication
script
var socket = new WebSocket("ws://127.0.0.1:8000/websocket");
socket.onopen = function () {
console.log("Connection opened.");
socket.send("Hello, server!");
};
socket.onmessage = function (event) {
console.log("Received message: " + event.data);
};
socket.onclose = function () {
console.log("Connection closed.");
};