請教一下,python怎么連接websocket
問題描述
現(xiàn)在在做一個項(xiàng)目,需要用到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:感謝各位,百度了好久都找不到解決辦法,樓上這位大神的應(yīng)該可以用的,不過我看不太懂,感恩,上谷歌果然有收獲,果斷棄用百度
這是別人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構(gòu)建的
相關(guān)文章:
1. 請教一下同一個數(shù)據(jù)高迸發(fā)操作的問題2. javascript - 想請教一下這個網(wǎng)頁中的自動旋轉(zhuǎn)和折疊部分是如何實(shí)現(xiàn)的3. javascript - 請教一下 better-scroll +vue 滾動的用法4. html5 - 前端面試碰到了一個緩存數(shù)據(jù)的問題,來論壇上請教一下5. javascript - 想請教一下,js中 function中參數(shù) e 到底是什么,每個條用的參數(shù) e的用法都不一樣?6. selenium - 請教一下 Python 爬蟲工具7. css3 - 請教一下,css如何使左右兩邊的div高度自適應(yīng)相等8. 前端 - 請教一下CSS3中translateZ和rotateY書寫順序的問題9. vue.js - Vue APP基于webpack的項(xiàng)目,它是獨(dú)立的項(xiàng)目嗎?我后臺是Java的,要如何實(shí)現(xiàn),跨域請求嗎?大牛請教一下謝謝10. java - 請教一下final修飾的局部變量存放在哪
