C++ 接入指南
通过 C++17 + 标准线程 使用 webrpc Native SDK,流程与官方 Go 示例对齐:登录 → 获取回调端口 → 收发数据。
简介
- SDK 为 C ABI(各平台
libwebrpc-*.h+ 动态库)。 - 本页示例可编译/运行(请替换占位符并放入对应平台库文件)。
- Token / 密码请到控制台 我的 Token 查看。
依赖与多平台
| 平台 | 头文件 | 链接库名(示意) |
|---|---|---|
| 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(按 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)。
完整示例
// main.cpp — Linux / macOS
#if defined(__APPLE__)
#include "libwebrpc-Mac.h"
#elif defined(__linux__) && defined(__aarch64__)
#include "libwebrpc-Linux-arm64.h"
#elif defined(__linux__)
#include "libwebrpc-Linux.h"
#else
#error "unsupported platform"
#endif
#include <arpa/inet.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <string>
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
#include <vector>
static bool readFull(int fd, void *buf, size_t n) {
char *p = static_cast<char *>(buf);
size_t got = 0;
while (got < n) {
ssize_t r = ::read(fd, p + got, n - got);
if (r <= 0) return false;
got += static_cast<size_t>(r);
}
return true;
}
static void handleDataStream(GoUintptr webrpc, int fd, uint32_t sessionId) {
uint32_t lenBe = 0;
if (!readFull(fd, &lenBe, 4)) return;
uint32_t len = ntohl(lenBe);
std::vector<char> data(len);
if (len && !readFull(fd, data.data(), len)) return;
if (len > 0 && len < 1024) {
std::cout << "Data content: " << std::string(data.begin(), data.end()) << std::endl;
}
int ret = WebrpcClient_SendData(webrpc, sessionId, const_cast<char *>("Received"), 8, 3000);
std::cout << "SendData ret = " << ret << std::endl;
}
static void handleFileStream(int fd, uint32_t sessionId) {
uint32_t nameLenBe = 0, dataLenBe = 0;
if (!readFull(fd, &nameLenBe, 4)) return;
uint32_t nameLen = ntohl(nameLenBe);
std::vector<char> name(nameLen);
if (nameLen && !readFull(fd, name.data(), nameLen)) return;
if (!readFull(fd, &dataLenBe, 4)) return;
uint32_t dataLen = ntohl(dataLenBe);
std::vector<char> file(dataLen);
if (dataLen && !readFull(fd, file.data(), dataLen)) return;
std::cout << "File stream sessionId=" << sessionId
<< " name=" << std::string(name.begin(), name.end())
<< " size=" << dataLen << std::endl;
}
static void callbackLoop(GoUintptr webrpc, int port) {
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) return;
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(static_cast<uint16_t>(port));
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (::connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0) {
perror("connect callback");
::close(fd);
return;
}
std::cout << "Connected to callback server, port: " << port << std::endl;
for (;;) {
uint32_t sidBe = 0;
uint8_t type = 0;
if (!readFull(fd, &sidBe, 4) || !readFull(fd, &type, 1)) break;
uint32_t sessionId = ntohl(sidBe);
if (type == 2) handleDataStream(webrpc, fd, sessionId);
else if (type == 1) handleFileStream(fd, sessionId);
else std::cout << "Unknown data type: " << static_cast<int>(type) << std::endl;
}
::close(fd);
}
int main() {
GoUintptr webrpc = WebrpcClient_New(const_cast<char *>("YOUR_TOKEN"),
const_cast<char *>("YOUR_PASSWORD"),
const_cast<char *>(""));
if (!webrpc) {
std::cerr << "WebrpcClient_New failed\n";
return 1;
}
std::cout << "Client handle: " << webrpc << std::endl;
for (;;) {
int status = WebrpcClient_LoginStatus(webrpc);
std::cout << "Login status: " << status << std::endl;
if (status != 0) break;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
int port = WebrpcClient_GetReceivePort(webrpc);
std::cout << "Callback TCP port: " << port << std::endl;
std::thread(callbackLoop, webrpc, port).detach();
for (;;) {
std::cout << "Session count = " << WebrpcClient_SessionSize(webrpc) << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
}
// WebrpcClient_Free(webrpc);
return 0;
}
/*
Build (macOS):
c++ -std=c++17 -O2 -o webrpc_demo main.cpp -I. -L. -lwebrpc-Mac -lpthread
*/
常见问题
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 示例。