why is gevent-websocket synchronous?

后端 未结 2 1788
独厮守ぢ
独厮守ぢ 2020-12-29 15:05

I am playing with gevent and websockets. This is a simple echo server:

from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHand         


        
2条回答
  •  情歌与酒
    2020-12-29 15:49

    The actual problem is this: data = ws.receive()

    What is happening here is your websocket is now waiting for a SINGLE connection while the whole app just hangs out.

    You have two solutions, either add a timeout to ws.receive() OR set it up as a high level application:

    from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
    
    class EchoApplication(WebSocketApplication):
        def on_open(self):
            print "Connection opened"
    
        def on_message(self, message):
            self.ws.send(message)
    
        def on_close(self, reason):
            print reason
    
    WebSocketServer(('', 8000), Resource({'/': EchoApplication}).serve_forever()
    

    as exampled here: https://pypi.python.org/pypi/gevent-websocket/

    This would then setup your process totally async, thus sending and receiving wouldn't compete for the same resource.

提交回复
热议问题