webrpc

中文版:打开中文文章

Go Integration Guide

Use the webrpc Native SDK via CGO binding to the official C ABI, 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


package main



/*

#cgo CFLAGS: -I.

#cgo darwin LDFLAGS: -L. -lwebrpc-Mac

#cgo linux,amd64 LDFLAGS: -L. -lwebrpc-Linux

#cgo linux,arm64 LDFLAGS: -L. -lwebrpc-Linux-arm64

#cgo windows LDFLAGS: -L. -lwebrpc-Windows



#if defined(__APPLE__)

#include "libwebrpc-Mac.h"

#elif defined(_WIN32)

#include "libwebrpc-Windows.h"

#elif defined(__linux__) && defined(__aarch64__)

#include "libwebrpc-Linux-arm64.h"

#elif defined(__linux__)

#include "libwebrpc-Linux.h"

#else

#error "unsupported platform: put the matching libwebrpc-*.h next to this file"

#endif



#include <stdlib.h>

*/

import "C"



import (

	"encoding/binary"

	"fmt"

	"io"

	"log"

	"net"

	"os"

	"os/signal"

	"syscall"

	"time"

	"unsafe"

)



func startReceivingCallbackData(webrpc C.GoUintptr, tcpPort int) {

	conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", tcpPort))

	if err != nil {

		log.Printf("Failed to connect callback server: %v", err)

		return

	}

	defer conn.Close()

	log.Printf("Connected to callback server, port: %d", tcpPort)



	for {

		sessionIdBytes := make([]byte, 4)

		if _, err := io.ReadFull(conn, sessionIdBytes); err != nil {

			log.Printf("callback read sessionId: %v", err)

			return

		}

		sessionId := binary.BigEndian.Uint32(sessionIdBytes)



		dataTypeBytes := make([]byte, 1)

		if _, err := io.ReadFull(conn, dataTypeBytes); err != nil {

			log.Printf("callback read type: %v", err)

			return

		}

		dataType := dataTypeBytes[0]

		log.Printf("Callback - sessionId=%d type=%d", sessionId, dataType)



		switch dataType {

		case 2:

			handleDataStream(webrpc, conn, sessionId)

		case 1:

			handleFileStream(conn, sessionId)

		default:

			log.Printf("Unknown data type: %d", dataType)

		}

	}

}



func handleDataStream(webrpc C.GoUintptr, conn net.Conn, sessionId uint32) {

	lenBytes := make([]byte, 4)

	if _, err := io.ReadFull(conn, lenBytes); err != nil {

		log.Printf("read data length: %v", err)

		return

	}

	dataLength := binary.BigEndian.Uint32(lenBytes)

	data := make([]byte, dataLength)

	if _, err := io.ReadFull(conn, data); err != nil {

		log.Printf("read data: %v", err)

		return

	}

	if dataLength > 0 && dataLength < 1024 {

		log.Printf("Data content: %s", string(data))

	}



	go func() {

		msg := "Received"

		cmsg := C.CString(msg)

		defer C.free(unsafe.Pointer(cmsg))

		ret := C.WebrpcClient_SendData(webrpc, C.uint(sessionId), cmsg, C.int(len(msg)), 3000)

		log.Println("SendData ret =", ret)

	}()

}



func handleFileStream(conn net.Conn, sessionId uint32) {

	nameLenBytes := make([]byte, 4)

	if _, err := io.ReadFull(conn, nameLenBytes); err != nil {

		return

	}

	nameLen := binary.BigEndian.Uint32(nameLenBytes)

	name := make([]byte, nameLen)

	if _, err := io.ReadFull(conn, name); err != nil {

		return

	}

	dataLenBytes := make([]byte, 4)

	if _, err := io.ReadFull(conn, dataLenBytes); err != nil {

		return

	}

	dataLen := binary.BigEndian.Uint32(dataLenBytes)

	fileData := make([]byte, dataLen)

	if _, err := io.ReadFull(conn, fileData); err != nil {

		return

	}

	log.Printf("File stream sessionId=%d name=%s size=%d", sessionId, string(name), dataLen)

}



func main() {

	token := C.CString("YOUR_TOKEN")

	passwd := C.CString("YOUR_PASSWORD")

	permission := C.CString("")

	defer C.free(unsafe.Pointer(token))

	defer C.free(unsafe.Pointer(passwd))

	defer C.free(unsafe.Pointer(permission))



	webrpc := C.WebrpcClient_New(token, passwd, permission)

	if webrpc == 0 {

		log.Fatal("WebrpcClient_New failed")

	}

	fmt.Printf("Client handle: %v\n", webrpc)



	for {

		status := C.WebrpcClient_LoginStatus(webrpc)

		fmt.Printf("Login status: %d\n", int(status))

		if status != 0 {

			break

		}

		time.Sleep(2 * time.Second)

	}



	tcpPort := int(C.WebrpcClient_GetReceivePort(webrpc))

	fmt.Printf("Callback TCP port: %d\n", tcpPort)

	go startReceivingCallbackData(webrpc, tcpPort)



	// Optional: open a session to a peer

	// peer := C.CString("PEER_TOKEN")

	// defer C.free(unsafe.Pointer(peer))

	// sid := C.WebrpcClient_OpenSession(webrpc, peer, permission)

	// log.Println("OpenSession id =", uint32(sid))



	stop := make(chan os.Signal, 1)

	signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)



	ticker := time.NewTicker(3 * time.Second)

	defer ticker.Stop()

	for {

		select {

		case <-ticker.C:

			log.Println("Session count =", C.WebrpcClient_SessionSize(webrpc))

		case <-stop:

			C.WebrpcClient_Free(webrpc)

			log.Println("freed, exit")

			return

		}

	}

}



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