webrpc

本文另有英文版:English version

Rust 接入指南

通过 extern "C" FFI 使用 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)。

完整示例


// Cargo.toml:

// [dependencies]

// libc = "0.2"

//

// build.rs optional; or place .dylib/.so in rustc link path.

// RUSTFLAGS='-L .' cargo run



use std::io::{Read, Result as IoResult};

use std::net::TcpStream;

use std::os::raw::{c_char, c_int, c_longlong, c_ushort};

use std::ffi::CString;

use std::thread;

use std::time::Duration;



pub type GoUintptr = usize;



#[link(name = "webrpc-Mac")] // change: webrpc-Linux / webrpc-Linux-arm64 / webrpc-Windows

unsafe extern "C" {

    fn WebrpcClient_New(token: *const c_char, passwd: *const c_char, permission: *const c_char) -> GoUintptr;

    fn WebrpcClient_LoginStatus(handle: GoUintptr) -> c_int;

    fn WebrpcClient_GetReceivePort(handle: GoUintptr) -> c_int;

    fn WebrpcClient_OpenSession(handle: GoUintptr, to_token: *const c_char, permission: *const c_char) -> u32;

    fn WebrpcClient_SessionSize(handle: GoUintptr) -> c_ushort;

    fn WebrpcClient_SendData(

        handle: GoUintptr,

        session_id: u32,

        data: *const c_char,

        data_len: c_int,

        time_out: c_longlong,

    ) -> c_int;

    fn WebrpcClient_Free(handle: GoUintptr);

}



fn read_u32_be(stream: &mut TcpStream) -> IoResult<u32> {

    let mut buf = [0u8; 4];

    stream.read_exact(&mut buf)?;

    Ok(u32::from_be_bytes(buf))

}



fn handle_data_stream(webrpc: GoUintptr, stream: &mut TcpStream, session_id: u32) -> IoResult<()> {

    let len = read_u32_be(stream)? as usize;

    let mut data = vec![0u8; len];

    if len > 0 {

        stream.read_exact(&mut data)?;

    }

    if len > 0 && len < 1024 {

        println!("Data content: {}", String::from_utf8_lossy(&data));

    }

    let msg = CString::new("Received").unwrap();

    let ret = unsafe {

        WebrpcClient_SendData(webrpc, session_id, msg.as_ptr(), 8, 3000)

    };

    println!("SendData ret = {ret}");

    Ok(())

}



fn handle_file_stream(stream: &mut TcpStream, session_id: u32) -> IoResult<()> {

    let name_len = read_u32_be(stream)? as usize;

    let mut name = vec![0u8; name_len];

    if name_len > 0 {

        stream.read_exact(&mut name)?;

    }

    let file_len = read_u32_be(stream)? as usize;

    let mut file = vec![0u8; file_len];

    if file_len > 0 {

        stream.read_exact(&mut file)?;

    }

    println!(

        "File stream sessionId={session_id} name={} size={file_len}",

        String::from_utf8_lossy(&name)

    );

    Ok(())

}



fn callback_loop(webrpc: GoUintptr, port: i32) {

    let addr = format!("127.0.0.1:{port}");

    let mut stream = match TcpStream::connect(&addr) {

        Ok(s) => s,

        Err(e) => {

            eprintln!("connect callback: {e}");

            return;

        }

    };

    println!("Connected to callback server, port: {port}");

    loop {

        let session_id = match read_u32_be(&mut stream) {

            Ok(v) => v,

            Err(_) => break,

        };

        let mut t = [0u8; 1];

        if stream.read_exact(&mut t).is_err() {

            break;

        }

        match t[0] {

            2 => {

                let _ = handle_data_stream(webrpc, &mut stream, session_id);

            }

            1 => {

                let _ = handle_file_stream(&mut stream, session_id);

            }

            other => println!("Unknown data type: {other}"),

        }

    }

}



fn main() {

    let token = CString::new("YOUR_TOKEN").unwrap();

    let passwd = CString::new("YOUR_PASSWORD").unwrap();

    let permission = CString::new("").unwrap();



    let webrpc = unsafe { WebrpcClient_New(token.as_ptr(), passwd.as_ptr(), permission.as_ptr()) };

    if webrpc == 0 {

        panic!("WebrpcClient_New failed");

    }

    println!("Client handle: {webrpc}");



    loop {

        let status = unsafe { WebrpcClient_LoginStatus(webrpc) };

        println!("Login status: {status}");

        if status != 0 {

            break;

        }

        thread::sleep(Duration::from_secs(2));

    }



    let port = unsafe { WebrpcClient_GetReceivePort(webrpc) };

    println!("Callback TCP port: {port}");

    thread::spawn(move || callback_loop(webrpc, port));



    loop {

        let n = unsafe { WebrpcClient_SessionSize(webrpc) };

        println!("Session count = {n}");

        thread::sleep(Duration::from_secs(3));

    }

    // unsafe { WebrpcClient_Free(webrpc); }

}



常见问题

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 · 博客