如何让gevent websockets工作?

时间:2016-07-06 18:35:34

标签: python websocket gevent

我正在使用geventwebsockets但是甚至无法让示例应用运行起来。下面的代码给出了错误:

  

Traceback(最近一次调用最后一次):文件   " /usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py" ;,第884行,   在handle_one_response中       self.run_application()File" /usr/local/lib/python2.7/dist-packages/geventwebsocket/handler.py",   第88行,在run_application中       return super(WebSocketHandler,self).run_application()File" /usr/local/lib/python2.7/dist-packages/gevent/pywsgi.py" ;,第870行,   在run_application中       self.result = self.application(self.environ,self.start_response)文件   " /usr/local/lib/python2.7/dist-packages/geventwebsocket/resource.py" ;,   第90行,在通话中       引发异常("没有定义应用程序")例外:没有定义应用程序

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()

我一直在圈子里跑来跑去。谁能帮我吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

对你有用吗<​​/ p>

如果添加echo_app

def echo_app(environ, start_response):
    websocket = environ.get("wsgi.websocket")

    if websocket is None:
        return http_handler(environ, start_response)
    try:
        while True:
            message = websocket.receive()
            websocket.send(message)
        websocket.close()
    except geventwebsocket.WebSocketError, ex:
        print "{0}: {1}".format(ex.__class__.__name__, ex)

和 传递它

print "Running %s from %s" % (agent, path)
WebSocketServer(("", 8000), echo_app, debug=False).serve_forever()

如图
所示 https://bitbucket.org/noppo/gevent-websocket/src/0df192940acd288e8a8f6d2dd30329a3381c90f1/examples/echoserver.py