webrpc

中文版:打开中文文章

Python Integration Guide

Use the webrpc Native SDK via ctypes loading the shared library, matching the official Go sample flow: login → callback port → send/receive.

Overview

Dependencies & platforms

PlatformHeaderLink library (typical)
macOSlibwebrpc-Mac.h-lwebrpc-Mac
Linux x86_64libwebrpc-Linux.h-lwebrpc-Linux
Linux arm64libwebrpc-Linux-arm64.h-lwebrpc-Linux-arm64
Windowslibwebrpc-Windows.hwebrpc-Windows (see .lib / .dll in the SDK zip)

Download the matching SDK from the console, place the header and shared library next to your project (or configure include/lib paths).

Replace YOUR_TOKEN / YOUR_PASSWORD with real values from My Tokens.

Integration flow

Typical lifecycle:

1. WebrpcClient_New

2. Poll WebrpcClient_LoginStatus until non-zero

3. WebrpcClient_GetReceivePort

4. Background thread connects to the callback port and parses frames

5. Optional: WebrpcClient_OpenSession to dial a peer

6. Main loop may print WebrpcClient_SessionSize

7. WebrpcClient_Free before exit

Native API reference

APIDescription
WebrpcClient_New(token, passwd, permission)Create a client handle (uintptr). permission may be an empty string.
WebrpcClient_LoginStatus(handle)Login status; non-zero means ready.
WebrpcClient_GetReceivePort(handle)Local callback TCP port on 127.0.0.1.
WebrpcClient_OpenSession(handle, toToken, permission)Open a session to a peer token; returns sessionId.
WebrpcClient_SessionSize(handle)Current session count.
WebrpcClient_TarTokenBySession(handle, sessionId)Peer token for a session.
WebrpcClient_CloseSession(handle, sessionId)Close a session.
WebrpcClient_SendData(handle, sessionId, data, dataLen, timeOutMs)Send bytes; timeOutMs is timeout in milliseconds.
WebrpcClient_SendFile(handle, sessionId, filePath)Send a file.
WebrpcClient_Free(handle)Free the client. Always call before exit.

Callback TCP protocol

After the client is created, the SDK opens a local TCP callback port. Your process should connect("127.0.0.1", port) and read frames in a loop:


sessionId : uint32 big-endian (4 bytes)

type      : uint8 (1 byte)

  - 2 = data stream

  - 1 = file stream

Data stream (type=2)


dataLen : uint32 BE

payload : dataLen bytes

File stream (type=1)


nameLen  : uint32 BE

fileName : nameLen bytes

dataLen  : uint32 BE

fileData : dataLen bytes

On a data stream, the sample replies with WebrpcClient_SendData(..., "Received", ..., 3000).

Complete example


#!/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()



FAQ

1. Cannot find the shared library

Ensure -L. / LD_LIBRARY_PATH / DYLD_LIBRARY_PATH / java.library.path points at the SDK library folder.

2. LoginStatus stays 0

Verify token/password, network access, and that you loaded the correct platform SDK.

3. Callback connect fails

Connect to 127.0.0.1:port after GetReceivePort. Do not hard-code the port.

4. Dial a peer

Call WebrpcClient_OpenSession(handle, peerToken, permission), then SendData with the returned sessionId.

5. Windows

The C/C++ samples use POSIX sockets. On Windows prefer Go / Java / Python / Rust, or adapt the TCP code to Winsock.

Download SDK · Blog