码迷,mamicode.com
首页 > 编程语言 > 详细

python实现建立websocket通信

时间:2019-12-08 14:07:23      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:class   div   关闭   建立   mes   star   imp   span   成功   

实现代码如下:

#websocket协议通信
import threading
import time
import websocket

def when_message(ws, message):
    print(‘/n接收到的消息:‘ + message)
# 当建立连接后,死循环不断输入消息发送给服务器
# 这里需要另起一个线程
def when_open(ws):
    print(‘连接成功‘)
    def run():
        while True:
            a = input(‘请输入:‘)
            ws.send(a)
            time.sleep(0.5)
            if a == ‘close‘:
                ws.close()
                break
    t = threading.Thread(target=run)
    # t.setDaemon(True)
    t.start()
def when_close(ws):
    print(‘连接关闭‘)

if __name__ == ‘__main__‘:
    ws = websocket.WebSocketApp(‘ws://localhost:9999/‘, on_message=when_message, on_open=when_open, on_close=when_close)
    ws.run_forever()

 

python实现建立websocket通信

标签:class   div   关闭   建立   mes   star   imp   span   成功   

原文地址:https://www.cnblogs.com/badbadboyyx/p/12005565.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!