33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""
|
|
隧道控制面协议:服务端与客户端之间 JSON 文本行。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
|
|
def register_message(worker_id: str, local_port: int) -> dict:
|
|
"""客户端注册:暴露的 worker_id 与本地端口。"""
|
|
return {"type": "register", "worker_id": worker_id, "local_port": local_port}
|
|
|
|
|
|
def register_ack_message(proxy_port: int) -> dict:
|
|
"""服务端确认:分配给的代理端口。"""
|
|
return {"type": "register_ack", "proxy_port": proxy_port}
|
|
|
|
|
|
def open_stream_message(stream_id: int, local_port: int) -> dict:
|
|
"""服务端通知客户端:请为 stream_id 打开本地 local_port 并连到 stream 端口。"""
|
|
return {"type": "open_stream", "stream_id": stream_id, "local_port": local_port}
|
|
|
|
|
|
def encode_control(msg: dict) -> bytes:
|
|
"""编码为一行 JSON + 换行。"""
|
|
return (json.dumps(msg, ensure_ascii=False) + "\n").encode("utf-8")
|
|
|
|
|
|
def decode_control(line: bytes) -> dict:
|
|
"""解码一行 JSON。"""
|
|
return json.loads(line.decode("utf-8").strip())
|