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