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



我正在尝试在greenlet中接收websocket消息,但似乎不起作用。我有这个代码:

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

以及:

line 197, in read_frame
header = Header.decode_header(self.stream)

我该如何解决这个问题?

这里有一个我所做的非常好的例子
带瓶子和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连接,像往常一样发送和接收数据。

相关内容

  • 没有找到相关文章

最新更新