這段程式碼使用 Streamlit 建立一個 WebSocket 測試介面,當使用者按下按鈕時,會透過 WebSocket 用戶端向伺服器發送訊息,並顯示伺服器的回應。同時,它會在背景啟動 WebSocket 伺服器(如果尚未啟動),允許用戶端與其通訊,適用於即時通訊測試、開發 WebSocket 服務或簡單的雙向訊息傳遞應用。
0
0
0
1
| 1 | import asyncio |
| 2 | import websockets |
| 3 | import streamlit as st |
| 4 | import threading |
| 5 | import socket |
| 6 | |
| 7 | # Function to check if a port is free |
| 8 | def is_port_free(port): |
| 9 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 10 | return s.connect_ex(('localhost', port)) != 0 |