請教一下,python怎么連接websocket
問題描述
現在在做一個項目,需要用到websocket,需要python去連接websocket,但是不知道怎么用python連接websocket,找了好久沒找到,求各位大佬幫忙~~
問題解答
回答1:flask 使用 gevent-websocket + gunicorn 部署pip3 install gevent-websocketpip3 install gunicorn
app.py demo
from geventwebsocket.handler import WebSocketHandlerfrom gevent.pywsgi import WSGIServerapp = 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:appdjango 使用 Django-websocket
https://github.com/archever/p...
回答2:感謝各位,百度了好久都找不到解決辦法,樓上這位大神的應該可以用的,不過我看不太懂,感恩,上谷歌果然有收獲,果斷棄用百度
這是別人github上面的,可以用
# install ws4py# pip install ws4py# easy_install ws4pyfrom ws4py.client.threadedclient import WebSocketClientclass 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 mif __name__ == ’__main__’: try:ws = DummyClient(’ws://10.222.138.163:1889/websocket’, protocols=[’chat’])ws.connect()ws.run_forever() except KeyboardInterrupt:ws.close()回答3:
建議使用tornado,它支持websocket,知乎后端就是使用tornado構建的
相關文章:
1. 請教一下同一個數據高迸發操作的問題2. selenium - 請教一下 Python 爬蟲工具3. vue.js - Vue APP基于webpack的項目,它是獨立的項目嗎?我后臺是Java的,要如何實現,跨域請求嗎?大牛請教一下謝謝4. 前端 - 請教一下CSS3中translateZ和rotateY書寫順序的問題5. java - 請教一下final修飾的局部變量存放在哪6. css3 - 請教一下,css如何使左右兩邊的div高度自適應相等7. 請教一下,eclipse設置好了build automatically后,什么時候自動構建java源文件?8. javascript - 想請教一下,js中 function中參數 e 到底是什么,每個條用的參數 e的用法都不一樣?9. javascript - 請教一下 better-scroll +vue 滾動的用法10. html5 - 前端面試碰到了一個緩存數據的問題,來論壇上請教一下
