服务端
搭建服务端¶
使用 DGLabWSServer。
参数说明¶
DGLabWSServer ¶
示例¶
import asyncio
from pydglab_ws.server import DGLabWSServer
async def main():
async with DGLabWSServer("0.0.0.0", 5678, 60):
await asyncio.Future()
获取连接到服务端的 终端/App 信息¶
可获取到 终端/App 的 ID 以及其对应的WebSocket 连接对象和相互的绑定关系。通过 WebSocket 连接对象,可以获取连接延迟等信息。
可用属性¶
client_id_to_target_id
property
¶
client_id_to_target_id: Dict[UUID4, UUID4]
client_id 到 target_id 的映射
target_id_to_client_id
property
¶
target_id_to_client_id: Dict[UUID4, UUID4]
target_id 到 client_id 的映射
uuid_to_ws
property
¶
uuid_to_ws: Dict[UUID4, WebSocketServerProtocol]
所有的 WebSocket 客户端 ID(包含终端与 App)到 WebSocket 连接对象的映射
示例¶
from pydglab_ws.server import DGLabWSServer
async def main():
async with DGLabWSServer("0.0.0.0", 5678, 60) as server:
... # 设备连接后
for target_id in server.target_id_to_client_id.keys():
websocket = server.uuid_to_ws[target_id]
print(f"App {target_id} 延迟为 {websocket.latency} 秒")
print(f"目前已连接 {len(server.local_client_ids)} 个 本地终端")
添加回调函数,在连接建立/断开或收到指定类型的消息后调用¶
通过 DGLabWSServer 的几个方法添加和删除回调函数。
可用方法¶
add_receive_callback ¶
remove_receive_callback ¶
add_connection_callback ¶
add_connection_callback(mode: Literal['new_connect', 'disconnect'], func: Callable[[UUID4, WebSocketServerProtocol], Any]) -> bool
添加回调函数,在新的 WebSocket 连接建立时(新客户端)或连接断开时调用
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode |
Literal['new_connect', 'disconnect']
|
类型, |
required |
func |
Callable[[UUID4, WebSocketServerProtocol], Any]
|
回调函数,传入 终端 / App 的 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
remove_connection_callback ¶
remove_connection_callback(mode: Literal['new_connect', 'disconnect'], func: Callable[[UUID4, WebSocketServerProtocol], Any]) -> bool
删除在新的 WebSocket 连接建立时(新客户端)或连接断开时调用的回调函数
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode |
Literal['new_connect', 'disconnect']
|
类型, |
required |
func |
Callable[[UUID4, WebSocketServerProtocol], Any]
|
回调函数,传入 终端 / App 的 |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
创建本地终端¶
查看 与本地终端一体的服务端