Python實現websockets客戶端

Python websockets庫是用於在Python中構建WebSocket服務器和客戶端的庫。參考文檔(https://www.yiibai.com/websocket/python-websockets-library.htmlhttps://websockets.readthedocs.io/en/stable/intro.html

關於async異步文檔見(python3.7 https://docs.python.org/zh-cn/3.7/library/asyncio.html#module-asyncio; python3.6 https://docs.python.org/zh-cn/3.6/library/asyncio-task.html#asyncio-example-gather

#-*-coding:utf-8-*-

import asyncio
import websockets
import json
post_data = {"data":"消息"}
async def send_data():
    uri = "ws://127.0.01:9501"
    async with websockets.connect(uri) as websocket:
        print(bytes(json.dumps(post_data, ensure_ascii=False).encode("utf-8")))
        await websocket.send(bytes(json.dumps(post_data, ensure_ascii=False).encode("utf-8")))
        greeting = await websocket.recv()
        print(greeting)

loop = asyncio.get_event_loop()
loop.run_until_complete(send_data())
loop.close()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章