我正在尝试构建一个Python瓶子应用程序,该应用程序使用gevent,并且遇到了麻烦。我正在使用以下版本的软件:
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“。我环顾过谷歌,但到目前为止,我所做的一切都没有起到任何作用。
发布于 2022-04-19 21:31:33
下面是一个对我非常有用的例子。您确实应该使用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()https://stackoverflow.com/questions/30357904
复制相似问题