首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >gevent-socketio与Python瓶

gevent-socketio与Python瓶
EN

Stack Overflow用户
提问于 2015-05-20 18:42:05
回答 1查看 453关注 0票数 2

我正在尝试构建一个Python瓶子应用程序,该应用程序使用gevent,并且遇到了麻烦。我正在使用以下版本的软件:

Python: 2.7.5

socketio: 0.3.5

socket.io.js: 1.3.5

在我的主要代码中,我以这种方式运行这个应用程序:

代码语言:javascript
复制
SocketIOServer(("0.0.0.0", port), application, resource="socket.io", transports=["websocket"]).serve_forever()

这就是我的服务器处理程序的一部分:

代码语言:javascript
复制
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看起来是这样的:

代码语言: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“。我环顾过谷歌,但到目前为止,我所做的一切都没有起到任何作用。

EN

回答 1

Stack Overflow用户

发布于 2022-04-19 21:31:33

下面是一个对我非常有用的例子。您确实应该使用gevent中内置的websocket库,这简化了整个连接处理。显然,如果您想要使用这个,您需要导入您自己的API路由.

代码语言:javascript
复制
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()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30357904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档