Rust Integration Guide
Use the webrpc Native SDK via extern "C" FFI, matching the official Go sample flow: login → callback port → send/receive.
Overview
- The SDK exposes a C ABI (
libwebrpc-*.h+ shared library per platform). - The sample below is meant to be buildable/runnable after you replace placeholders and place the correct platform library files.
- Get token/password from My Tokens in the console.
Dependencies & platforms
| Platform | Header | Link library (typical) |
|---|---|---|
| macOS | libwebrpc-Mac.h | -lwebrpc-Mac |
| Linux x86_64 | libwebrpc-Linux.h | -lwebrpc-Linux |
| Linux arm64 | libwebrpc-Linux-arm64.h | -lwebrpc-Linux-arm64 |
| Windows | libwebrpc-Windows.h | webrpc-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_PASSWORDwith 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
| API | Description |
|---|---|
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
// 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); }
}
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.