Heim  >  Fragen und Antworten  >  Hauptteil

Bitte sagen Sie mir, wie ich einen WebSocket in Python verbinde

Ich arbeite gerade an einem Projekt, das die Verwendung von WebSocket erfordert, aber ich weiß nicht, wie ich Python verwenden soll, um eine Verbindung zum WebSocket herzustellen Zeit und habe es nicht gefunden. Bitte helfen Sie mir ~~

phpcn_u1582phpcn_u15822711 Tage vor843

Antworte allen(3)Ich werde antworten

  • 我想大声告诉你

    我想大声告诉你2017-05-18 10:56:01

    flask 使用 gevent-websocket + gunicorn 部署

    pip3 install gevent-websocket
    pip3 install gunicorn

    app.py demo

    from geventwebsocket.handler import WebSocketHandler
    from gevent.pywsgi import WSGIServer
    
    app = Flask(__name__)
    
    @app.route('/echo/')
    def echo():
        if request.environ.get('wsgi.websocket'):
            ws = request.environ['wsgi.websocket']
            while True:
                msg = ws.receive()
                ws.send(msg)
    
    if __name__ == '__main__':
        http_server = WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
        http_server.serve_forever()

    使用 gunicorn 启动 指定用 gevent-websocket

    gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker app:app

    django 使用 Django-websocket

    https://github.com/archever/p...

    Antwort
    0
  • 为情所困

    为情所困2017-05-18 10:56:01

    感谢各位,百度了好久都找不到解决办法,楼上这位大神的应该可以用的,不过我看不太懂,感恩,上谷歌果然有收获,果断弃用百度

    这是别人github上面的,可以用

    # install ws4py
    # pip install ws4py
    # easy_install ws4py
    from ws4py.client.threadedclient import WebSocketClient
    
    class DummyClient(WebSocketClient):
        def opened(self):
            self.send("www.baidu.com")
    
        def closed(self, code, reason=None):
            print "Closed down", code, reason
    
        def received_message(self, m):
            print m
    
    if __name__ == '__main__':
        try:
            ws = DummyClient('ws://10.222.138.163:1889/websocket', protocols=['chat'])
            ws.connect()
            ws.run_forever()
        except KeyboardInterrupt:
            ws.close()

    Antwort
    0
  • 怪我咯

    怪我咯2017-05-18 10:56:01

    建议使用tornado,它支持websocket,知乎后端就是使用tornado构建的

    Antwort
    0
  • StornierenAntwort