webrpc

中文版:打开中文文章

PHP Integration Guide

Use the webrpc Native SDK via PHP FFI extension, 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


<?php

/**

 * Requires PHP FFI extension (php-ffi).

 * Place libwebrpc-*.dylib/.so next to this script or use absolute path.

 *

 *   php main.php

 */



function platformLib(): string {

    $os = PHP_OS_FAMILY;

    $arch = php_uname('m');

    if ($os === 'Darwin') return __DIR__ . '/libwebrpc-Mac.dylib';

    if ($os === 'Windows') return __DIR__ . '/webrpc-Windows.dll';

    if (str_contains($arch, 'aarch64') || str_contains($arch, 'arm64')) {

        return __DIR__ . '/libwebrpc-Linux-arm64.so';

    }

    return __DIR__ . '/libwebrpc-Linux.so';

}



$ffi = FFI::cdef('

    typedef unsigned long long GoUintptr;

    GoUintptr WebrpcClient_New(char* token, char* passwd, char* permission);

    int WebrpcClient_LoginStatus(GoUintptr handle);

    int WebrpcClient_GetReceivePort(GoUintptr handle);

    unsigned int WebrpcClient_OpenSession(GoUintptr handle, char* toToken, char* permission);

    unsigned short WebrpcClient_SessionSize(GoUintptr handle);

    int WebrpcClient_SendData(GoUintptr handle, unsigned int sessionId, char* data, int dataLen, long long timeOut);

    void WebrpcClient_Free(GoUintptr handle);

', platformLib());



function readBytes($socket, int $length) {

    $data = '';

    while (strlen($data) < $length) {

        $chunk = fread($socket, $length - strlen($data));

        if ($chunk === false || $chunk === '') return false;

        $data .= $chunk;

    }

    return $data;

}



function handleDataStream($ffi, $webrpc, $socket, int $sessionId): void {

    $lenRaw = readBytes($socket, 4);

    if ($lenRaw === false) return;

    $len = unpack('N', $lenRaw)[1];

    $data = $len > 0 ? readBytes($socket, $len) : '';

    if ($data === false) return;

    if ($len > 0 && $len < 1024) echo "Data content: {$data}\n";

    $msg = "Received";

    $ret = $ffi->WebrpcClient_SendData($webrpc, $sessionId, $msg, strlen($msg), 3000);

    echo "SendData ret = {$ret}\n";

}



function handleFileStream($socket, int $sessionId): void {

    $nameLen = unpack('N', readBytes($socket, 4))[1];

    $name = readBytes($socket, $nameLen);

    $fileLen = unpack('N', readBytes($socket, 4))[1];

    $fileData = readBytes($socket, $fileLen);

    echo "File stream sessionId={$sessionId} name={$name} size={$fileLen}\n";

}



$token = "YOUR_TOKEN";

$passwd = "YOUR_PASSWORD";

$permission = "";



$webrpc = $ffi->WebrpcClient_New($token, $passwd, $permission);

if (!$webrpc) {

    fwrite(STDERR, "WebrpcClient_New failed\n");

    exit(1);

}

echo "Client handle: {$webrpc}\n";



while (true) {

    $status = $ffi->WebrpcClient_LoginStatus($webrpc);

    echo "Login status: {$status}\n";

    if ($status !== 0) break;

    sleep(2);

}



$port = $ffi->WebrpcClient_GetReceivePort($webrpc);

echo "Callback TCP port: {$port}\n";



$socket = fsockopen('127.0.0.1', $port);

if (!$socket) {

    fwrite(STDERR, "Failed to connect callback server\n");

    $ffi->WebrpcClient_Free($webrpc);

    exit(1);

}

stream_set_blocking($socket, true);

echo "Connected to callback server, port: {$port}\n";



// Simple single-threaded demo: process callbacks; print session size occasionally via time check

$last = time();

while (!feof($socket)) {

    if (time() - $last >= 3) {

        echo "Session count = " . $ffi->WebrpcClient_SessionSize($webrpc) . "\n";

        $last = time();

    }

    $sidRaw = readBytes($socket, 4);

    $typeRaw = readBytes($socket, 1);

    if ($sidRaw === false || $typeRaw === false) break;

    $sessionId = unpack('N', $sidRaw)[1];

    $type = ord($typeRaw);

    if ($type === 2) {

        handleDataStream($ffi, $webrpc, $socket, $sessionId);

    } elseif ($type === 1) {

        handleFileStream($socket, $sessionId);

    } else {

        echo "Unknown data type: {$type}\n";

    }

}



fclose($socket);

$ffi->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.

Download SDK · Blog