我正试图将一个使用geevent -socketio的Python瓶应用程序组合在一起,并且遇到了麻烦。我正在使用以下版本的软件:
Python: 2.7.5
Socketio: 0.3.5
socket.io.js: 1.3.5
在我的主代码中,我是这样运行应用程序的:
SocketIOServer(("0.0.0.0", port), application, resource="socket.io", transports=["websocket"]).serve_forever()
这是我的服务器处理程序的一部分:
class PingPongNamespace(BaseNamespace):
'''This class defines the websocket handler for
the press controller status system
'''
def __init__(self):
v = 1
def on_ping(self, msg):
self.emit("pong")
from socketio import socketio_manage
@app.route(mount("/socket.io/1/<path:path>"))
def pingpong(path):
socketio_manage(request.environ, {"/pingpong": PingPongNamespace}, request)
我的JavaScript是这样的:
$(document).ready(function() {
"use strict";
localStorage.debug = "*";
var socket = io.connect("http://" + window.location.host + "/pingpong");
socket.on("connect", function(data) {
console.log("join");
});
socket.on("pong", function(data) {
console.log("pong: " + data);
});
setInterval(function() {
console.log("ping");
socket.emit("ping");
}, 10 * 1000);
});
服务器运行,但我从未从客户端连接到服务器,我一直看到
KeyError:"socketio"
因为"socketio"未在服务器环境变量中定义。
这是一个对我来说非常有效的例子。你真的应该使用内置在gevent中的websocket库,这简化了整个连接处理。显然,如果你想使用这个,你需要导入你自己的API路由…
from gevent import monkey
monkey.patch_all()
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
import bottle
#websocket
@route('/ws/api')
def handle_websocket():
ws = request.environ.get('wsgi.websocket')
if not ws:
abort(400, 'Expected WebSocket request.')
while 1:
message = None
try:
with Timeout(2, False) as timeout: #keeps the websocket cycling so you can refresh data without waiting forever for input.
message = ws.receive()
if message:
message = json.dictcheck(message)
# print(message)
for command, payload in message.items():
wapi = a.API(payload) # call your api here
func = getattr(wapi, command, None)
if callable(func):
try:
x = func()
ws.send(json.jsoncheck({command:x}))
except Exception as exc:
traceback.print_exc()
ws.send(json.jsoncheck({'status': 'Error'}))
except WebSocketError:
break
except Exception as exc:
traceback.print_exc()
sleep(1)
if __name__ == '__main__':
botapp = bottle.app()
server = WSGIServer(("0.0.0.0", 80), botapp , handler_class=WebSocketHandler)
server.serve_forever()