为什么我不能在greenlet中使用gevent websockets

时间:2018-11-07 07:15:39

标签: python websocket gevent greenlets

我正在尝试以greenlet接收websocket消息,但似乎确实可行。我有以下代码:

\res\values\attrs.xml

并且在运行时,它将返回此错误:

import gevent
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketServer, WebSocketApplication, Resource



def recvWs(ws):
    gevent.sleep(0)
    recvedData = ws.receive()
    rData = json.loads(recvedData)
    print(rData)

def app(environ, start_response):


    websocket = environ['wsgi.websocket']

    while True:
        gevent.spawn(recvWs,websocket)
        gevent.sleep(0)

if __name__ == '__main__':
    server = WSGIServer(("0.0.0.0", 80), app,handler_class=WebSocketHandler)
    server.serve_forever()

以及:

<Greenlet "Greenlet-0" at 0x23fa4306148: 
recvWs(<geventwebsocket.websocket.WebSocket object at 0x0)> failed with 
RuntimeError

我该如何解决?

1 个答案:

答案 0 :(得分:0)

这是我所做的很好的例子。
带有bottle和gevent的Python:

from gevent import sleep as gsleep, Timeout
from geventwebsocket import WebSocketError
from bottle import Bottle, get, post, route, request, response, template, redirect, abort

@route('/ws/app')
def handle_websocket():
    wsock = request.environ.get('wsgi.websocket')
    if not wsock:
        abort(400, 'Expected WebSocket request.')
    # Send initial data here
    wsock.send(json.dumps(data))
    while 1:
        try:
            #Process incoming message.  2 second timeout to not block
            message = {}
            with Timeout(2, False) as timeout:
                message = wsock.receive()
            if message:
                message = json.loads(message)
                if isinstance(message, dict):
                     # Do something with data and return
                     wsock.send(json.dumps(result))
            # Add an additional second just for sanity.  Not necessarily needed
            gsleep(1)
        except WebSocketError:
            break
        except Exception as exc:
            traceback.print_exc()
            gsleep(2)

然后在您的JavaScript中打开Websocket连接,然后像往常一样发送和接收数据。