# Python Websocket
###### tags: `交接資料` `Python`
>author: NanoStar030、wcyan、JamesLai
>last update: 2024/02/15
---
## 一、Python Websocket 介紹
WebSocket 提供簡單的傳輸方法,使得伺服器能夠與前端應用或其他應用程序實現即時的雙向通信。

---
## 二、基本架構
> ~~~ python
> import asyncio
> import websockets
>
> async def handle_client(websocket): # 有用戶端連線(websocket代表了該用戶端)
> try:
> print("Client connected from {0}".format(websocket.remote_address))
> async for message in websocket: # 用戶端發送訊息
> await ReceivedStrData(websocket, message) # 對收到的訊息進行處理
> print("Client disconnected from {0}".format(websocket.remote_address)) # 用戶端的連線結束
> except:
> print("Client connected error")
>
> async def ReceivedStrData(websocket, data):
> print("{0} sent message: {1}".format(websocket.remote_address, data))
> await websocket.send("Message:Get Message Successfully") # 使用 send 發送訊息到指定的websocket
>
> async def main():
> server = await websockets.serve(handle_client, "172.0.0.1", 3000) # 開始伺服器
> print("Server started, listening on {0}".format(server.sockets[0].getsockname()))
> await server.wait_closed()
>
> if __name__ == "__main__":
> asyncio.run(main())
> ~~~
---
## 三、傳輸方法
1. 伺服器接受資料
> 在傳輸的字串中加入命令動作,伺服器再根據命令進行不同的資料處理
> "Command":"Value"
> ex. UpdateClient:Hololens, Message:Hello World
> ~~~ python
> async def ReceivedStrData(websocket, data):
> command, value = data.split(':')
> if command == "Message":
> print("{0} sent {1}".format(websocket.remote_address, value))
> await websocket.send("Message:Sent Successfully")
> else:
> await websocket.send("Message:Wrong Key Words")
>
2. 伺服器傳輸資料
> 伺服器要主動push資料到用戶端必須要記得target用戶端的參數,因此結合上面的接受資料方法
> ~~~ python
> HololensClient = null # 代表 hololens 用戶端的 global 變數
> async def ReceivedStrData(websocket, data):
> command, value = data.split(':')
> if command == "UpdateClient": # 該用戶端請求升級
> if value == "Hololens"
> global HololensClient
> HololensClient = websocket # 利用 global 變數儲存該用戶資訊
> print("{0} is new Hololens Client now".format(HololensClient.remote_address))
> await HololensClient.send("Message:Update Successfully")
> else:
> await websocket.send("Message:Wrong Key Words")
> ~~~
> 之後就可以使用該 global 變數隨時主動發送訊息
> ~~~ python
> async def SendDataToHololens(data):
> global HololensClient
> if not HololensClient == None:
> await HololensClient.send(data)
>
> SendDataToHololens("Message:Hello Hololens")
> ~~~
3. 用戶端
> 需要搭配 Unity Websocket 作為用戶端使用,參考 [Unity WebSocket](https://hackmd.io/@unityMRTKbreaker/Sy5sO0DtT)
---