webrpc

本文另有英文版:English version

Python 接入指南

通过 ctypes 加载动态库 使用 webrpc Native SDK,流程与官方 Go 示例对齐:登录 → 获取回调端口 → 收发数据。

简介

依赖与多平台

平台头文件链接库名(示意)
macOSlibwebrpc-Mac.h-lwebrpc-Mac
Linux x86_64libwebrpc-Linux.h-lwebrpc-Linux
Linux arm64libwebrpc-Linux-arm64.h-lwebrpc-Linux-arm64
Windowslibwebrpc-Windows.hwebrpc-Windows(按 SDK 包内实际 .lib / .dll)

请先在控制台「下载 SDK」获取对应平台文件,将头文件与动态库放到工程同级目录(或自行配置 include/lib 路径)。

将下方示例中的 YOUR_TOKEN / YOUR_PASSWORD 替换为「我的 Token」中的真实值。

接入流程

典型生命周期:

1. WebrpcClient_New 创建客户端

2. 轮询 WebrpcClient_LoginStatus 直到非 0

3. WebrpcClient_GetReceivePort 拿到回调端口

4. 后台线程连接回调端口,解析数据/文件帧

5. 可选:WebrpcClient_OpenSession 主动建连对端

6. 主循环可打印 WebrpcClient_SessionSize

7. 退出前 WebrpcClient_Free

Native API 一览

API说明
WebrpcClient_New(token, passwd, permission)创建客户端,返回句柄(uintptr)。permission 可传空字符串。
WebrpcClient_LoginStatus(handle)查询登录状态;返回值 != 0 表示已登录可用。
WebrpcClient_GetReceivePort(handle)获取本机回调 TCP 端口(监听在 127.0.0.1)。
WebrpcClient_OpenSession(handle, toToken, permission)主动打开到对端 token 的会话,返回 sessionId。
WebrpcClient_SessionSize(handle)当前会话数量。
WebrpcClient_TarTokenBySession(handle, sessionId)根据会话 ID 查询对端 token。
WebrpcClient_CloseSession(handle, sessionId)关闭指定会话。
WebrpcClient_SendData(handle, sessionId, data, dataLen, timeOutMs)向会话发送二进制/文本数据;timeOutMs 为超时毫秒。
WebrpcClient_SendFile(handle, sessionId, filePath)向会话发送文件。
WebrpcClient_Free(handle)释放客户端,程序退出前必须调用。

回调 TCP 协议

客户端创建成功后,SDK 在本机开启一个 TCP 回调端口。你的进程需要 connect("127.0.0.1", port),然后循环读取帧:


sessionId : uint32 big-endian (4 bytes)

type      : uint8 (1 byte)

  - 2 = 数据流 (data stream)

  - 1 = 文件流 (file stream)

数据流 (type=2)


dataLen : uint32 BE

payload : dataLen bytes

文件流 (type=1)


nameLen  : uint32 BE

fileName : nameLen bytes

dataLen  : uint32 BE

fileData : dataLen bytes

收到数据流后,示例会调用 WebrpcClient_SendData 回复 "Received"(超时 3000ms)。

完整示例


#!/usr/bin/env python3

"""ctypes binding for webrpc. Place libwebrpc-*.dylib/.so/.dll beside this file."""



from __future__ import annotations



import ctypes

import platform

import socket

import struct

import sys

import threading

import time

from ctypes import c_char_p, c_int, c_longlong, c_ushort, c_uint, c_void_p





def load_lib() -> ctypes.CDLL:

    system = platform.system()

    machine = platform.machine().lower()

    if system == "Darwin":

        name = "./libwebrpc-Mac.dylib"

    elif system == "Windows":

        name = "./webrpc-Windows.dll"

    elif machine in ("aarch64", "arm64"):

        name = "./libwebrpc-Linux-arm64.so"

    else:

        name = "./libwebrpc-Linux.so"

    return ctypes.CDLL(name)





lib = load_lib()

GoUintptr = ctypes.c_size_t



lib.WebrpcClient_New.argtypes = [c_char_p, c_char_p, c_char_p]

lib.WebrpcClient_New.restype = GoUintptr

lib.WebrpcClient_LoginStatus.argtypes = [GoUintptr]

lib.WebrpcClient_LoginStatus.restype = c_int

lib.WebrpcClient_GetReceivePort.argtypes = [GoUintptr]

lib.WebrpcClient_GetReceivePort.restype = c_int

lib.WebrpcClient_OpenSession.argtypes = [GoUintptr, c_char_p, c_char_p]

lib.WebrpcClient_OpenSession.restype = c_uint

lib.WebrpcClient_SessionSize.argtypes = [GoUintptr]

lib.WebrpcClient_SessionSize.restype = c_ushort

lib.WebrpcClient_SendData.argtypes = [GoUintptr, c_uint, c_char_p, c_int, c_longlong]

lib.WebrpcClient_SendData.restype = c_int

lib.WebrpcClient_Free.argtypes = [GoUintptr]

lib.WebrpcClient_Free.restype = None





def recv_exact(sock: socket.socket, n: int) -> bytes:

    data = b""

    while len(data) < n:

        chunk = sock.recv(n - len(data))

        if not chunk:

            raise ConnectionError("Connection closed")

        data += chunk

    return data





def handle_data_stream(webrpc: int, sock: socket.socket, session_id: int) -> None:

    data_len = struct.unpack(">I", recv_exact(sock, 4))[0]

    data = recv_exact(sock, data_len) if data_len else b""

    if 0 < data_len < 1024:

        print("Data content:", data.decode("utf-8", errors="ignore"))

    msg = b"Received"

    ret = lib.WebrpcClient_SendData(webrpc, session_id, msg, len(msg), 3000)

    print("SendData ret =", ret)





def handle_file_stream(sock: socket.socket, session_id: int) -> None:

    name_len = struct.unpack(">I", recv_exact(sock, 4))[0]

    file_name = recv_exact(sock, name_len).decode("utf-8", errors="ignore")

    file_len = struct.unpack(">I", recv_exact(sock, 4))[0]

    _ = recv_exact(sock, file_len)

    print(f"File stream sessionId={session_id} name={file_name} size={file_len}")





def callback_loop(webrpc: int, port: int) -> None:

    with socket.create_connection(("127.0.0.1", port)) as sock:

        print(f"Connected to callback server, port: {port}")

        while True:

            try:

                session_id = struct.unpack(">I", recv_exact(sock, 4))[0]

                data_type = recv_exact(sock, 1)[0]

            except ConnectionError:

                break

            if data_type == 2:

                handle_data_stream(webrpc, sock, session_id)

            elif data_type == 1:

                handle_file_stream(sock, session_id)

            else:

                print("Unknown data type:", data_type)





def main() -> None:

    webrpc = lib.WebrpcClient_New(b"YOUR_TOKEN", b"YOUR_PASSWORD", b"")

    if not webrpc:

        raise SystemExit("WebrpcClient_New failed")

    print("Client handle:", int(webrpc))



    while True:

        status = lib.WebrpcClient_LoginStatus(webrpc)

        print("Login status:", status)

        if status != 0:

            break

        time.sleep(2)



    port = lib.WebrpcClient_GetReceivePort(webrpc)

    print("Callback TCP port:", port)

    t = threading.Thread(target=callback_loop, args=(int(webrpc), port), daemon=True)

    t.start()



    try:

        while True:

            print("Session count =", lib.WebrpcClient_SessionSize(webrpc))

            time.sleep(3)

    finally:

        lib.WebrpcClient_Free(webrpc)





if __name__ == "__main__":

    main()



常见问题

1. 链接找不到库

确认 -L. / LD_LIBRARY_PATH / DYLD_LIBRARY_PATH / java.library.path 指向 SDK 动态库目录。

2. LoginStatus 一直为 0

检查 token/密码是否正确、机器网络是否可达、是否使用了对应平台的 SDK。

3. 回调连不上

必须在 GetReceivePort 之后连接 127.0.0.1:port,不要写死端口号。

4. 主动联系对端

使用 WebrpcClient_OpenSession(handle, peerToken, permission),成功后返回 sessionId,再 SendData。

5. Windows

C/C++ 示例以 POSIX 套接字为主;Windows 请改用 Winsock,或优先使用 Go / Java / Python / Rust 示例。

下载 SDK · 博客