npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@lmkdbd/peer_connection

v1.2.2

Published

一个优雅的对等网络连接库,支持 WebRTC、DRTC、WebSocket 等多种协议

Downloads

42

Readme

Peer Connection Library

一个优雅的对等网络连接库,提供统一的 PeerNode 类,支持 WebRTC、DRTC、WebSocket 等多种协议。

特性

🎯 统一节点: 一个 PeerNode 类既可作为服务器又可作为客户端
🔗 多协议支持: WebRTC、DRTC、WebSocket 统一接口
智能连接: 自动协议发现和连接策略选择
📡 分阶段初始化: 按需建立信令连接和注册
🎨 优雅 API: 简洁的配置,强大的功能
🚀 灵活部署: 既可提供服务也可纯客户端使用

安装

npm install @lmkdbd/peer-connection

核心概念

PeerNode

PeerNode 是本库的核心类,每个节点都是平等的对等体:

  • 服务模式: 通过 server 配置提供特定协议的服务
  • 客户端模式: 不配置 server 则为纯客户端
  • 双重身份: 同一个节点可以既提供服务又连接其他节点

配置结构

{
    did_key: DID对象,           // 节点身份标识
    signaling_url: string,     // 信令服务器地址
    handler?: Function,        // 消息处理器
    server?: {                 // 服务配置(可选)
        protocol: string,      // "webrtc" | "ws" | "drtc"
        port?: number,         // 服务端口
        url?: string,         // 服务URL
        // ... 其他协议特定配置
    }
}

快速开始

1. 启动信令服务器

首先需要启动信令服务器(参考 example/signaling_server.js):

import { createDrtcServer } from "@lmkdbd/signaling";

// 启动DRTC信令服务器
createDrtcServer({
    cert: "-----BEGIN CERTIFICATE-----\n...",
    key: "-----BEGIN PRIVATE KEY-----\n...",
    port: 9999,
});

console.log("信令服务器启动在: drtc://127.0.0.1:9999/fingerprint");

2. WebRTC 基本使用

基于 example/webrtc.js 的实际用法:

import { PeerNode } from "@lmkdbd/peer-connection";
import { generateDid } from "@lmkdbd/peer-connection/pkg/did";
import drpc from '@instun/drpc';

// 生成 DID 标识
const serverDid = await generateDid();
const clientDid = await generateDid();

// 信令服务器地址
const signalingUrl = "drtc://127.0.0.1:9999/f0f65e3bdf6a266a2a7fe9fc0c1592253dbef1727c6b04cadda7062d899920bc";

// 创建WebRTC服务节点
const server = new PeerNode({
    did_key: serverDid,
    signaling_url: signalingUrl,
    server: {
        protocol: "webrtc",
    },
    handler: {
        "test": (data) => {
            console.log("服务器收到:", data);
            return { msg: "hello world!", received: data };
        }
    }
});

// 启动服务器
await server.start();
console.log("服务器启动,DID:", serverDid.id);

// 创建客户端节点
const client = new PeerNode({
    did_key: clientDid,
    signaling_url: signalingUrl,
    // 注意:没有 server 配置 = 纯客户端模式
});

// 连接到服务器
const connection = await client.connectTo(serverDid.id);
const rpc = drpc.open(connection, { opened: true });

// 发送消息
const response = await rpc.test({ msg: "hello from client" });
console.log("收到响应:", response);

3. WebSocket 服务

基于 example/websocket.js 的用法:

// WebSocket 服务节点
const wsServer = new PeerNode({
    did_key: await generateDid(),
    signaling_url: "ws://127.0.0.1:9999",  // WebSocket信令服务器
    handler: {
        "test": (data) => {
            console.log("WebSocket服务器收到:", data);
            return { msg: "hello world!" };
        }
    },
    server: {
        protocol: "ws",
        port: 8820,
        url: "ws://127.0.0.1:8820",
    }
});

await wsServer.start();

// 客户端连接
const client = new PeerNode({
    did_key: await generateDid(),
    signaling_url: "ws://127.0.0.1:9999",
});

const conn = await client.connectTo(wsServer.getDid());

API 参考

PeerNode 类

构造函数

new PeerNode({
    did_key: Object,        // DID密钥对象
    signaling_url: string,  // 信令服务器地址
    handler?: Function,     // 消息处理器
    server?: {              // 服务配置
        protocol: string,   // 协议类型
        port?: number,     // 端口
        url?: string,      // 服务URL
        key?: string,      // SSL私钥(DRTC)
        cert?: string,     // SSL证书(DRTC)
    },
    iceServers?: Array,     // ICE服务器配置
})

方法

启动和控制
  • start(): 启动节点(根据配置自动判断服务或客户端模式)
  • stop(): 停止节点
  • isStarted(): 检查是否已启动
  • isServiceStarted(): 检查是否已启动服务
连接功能
  • connectTo(peer_did): 连接到其他节点
  • getDid(): 获取节点DID
  • getSignalingInfo(): 获取信令信息

协议详解

WebRTC

// WebRTC 服务配置
const webrtcNode = new PeerNode({
    did_key: await generateDid(),
    signaling_url: "drtc://127.0.0.1:9999/fingerprint",
    server: {
        protocol: "webrtc",
    },
    handler: {
        "ping": (data) => ({ pong: data.timestamp })
    },
    iceServers: [
        { urls: "stun:stun.l.google.com:19302" }
    ]
});

特点:

  • ✅ 点对点直连,低延迟
  • ✅ NAT 穿越能力
  • ✅ 无需开放端口
  • ⚠️ 需要信令服务器协助建立连接

WebSocket

// WebSocket 服务配置
const wsNode = new PeerNode({
    did_key: await generateDid(),
    signaling_url: "ws://127.0.0.1:9999",
    server: {
        protocol: "ws",
        port: 8080,
        url: "ws://127.0.0.1:8080",
    },
    handler: {
        "message": (data) => ({ echo: data.content })
    }
});

特点:

  • ✅ Web 浏览器兼容
  • ✅ HTTP 升级协议
  • ✅ 防火墙友好
  • ⚠️ 需要开放端口

DRTC

// DRTC 服务配置
const drtcNode = new PeerNode({
    did_key: await generateDid(),
    signaling_url: "drtc://127.0.0.1:9999/fingerprint",
    server: {
        protocol: "drtc",
        port: 8888,
        url: "drtc://127.0.0.1:8888",
        key: "path/to/server.key",
        cert: "path/to/server.crt",
    },
    handler: {
        "data": (data) => ({ processed: data.value * 2 })
    }
});

特点:

  • ✅ 高性能数据传输
  • ✅ 可靠的连接
  • ✅ SSL/TLS 加密
  • ⚠️ 需要证书配置

使用模式

1. 纯客户端模式

// 不配置 server,纯客户端使用
const client = new PeerNode({
    did_key: await generateDid(),
    signaling_url: signalingUrl,
    // 无 server 配置
});

// 可以连接任何协议的服务
await client.connectTo(webrtcServerDid);
await client.connectTo(wsServerDid);
await client.connectTo(drtcServerDid);

2. 服务提供模式

// 配置 server,提供特定协议服务
const server = new PeerNode({
    did_key: await generateDid(),
    signaling_url: signalingUrl,
    server: {
        protocol: "webrtc",  // 提供WebRTC服务
    },
    handler: handlers
});

await server.start();

3. 混合模式(推荐)

// 既提供服务又可连接其他节点
const hybridNode = new PeerNode({
    did_key: await generateDid(),
    signaling_url: signalingUrl,
    server: {
        protocol: "webrtc",
    },
    handler: handlers
});

await hybridNode.start();

// 作为服务器:自动处理入站连接
// 作为客户端:主动连接其他节点
const conn = await hybridNode.connectTo(otherNodeDid);

示例文件

运行示例

# 1. 启动信令服务器
node example/signaling_server.js

# 2. 在另一个终端运行WebRTC示例
node example/webrtc.js

# 3. 运行WebSocket示例
node example/websocket.js

示例文件说明

  • signaling_server.js: 信令服务器启动脚本
  • webrtc.js: WebRTC 协议完整示例
  • websocket.js: WebSocket 协议完整示例
  • drtc.js: DRTC 协议示例(待更新)

高级特性

服务器双重身份

// 节点A和节点B都是服务器,但也可以互相连接
const nodeA = new PeerNode({
    did_key: await generateDid(),
    signaling_url: signalingUrl,
    server: { protocol: "webrtc" },
    handler: handlersA
});

const nodeB = new PeerNode({
    did_key: await generateDid(),
    signaling_url: signalingUrl,
    server: { protocol: "webrtc" },
    handler: handlersB
});

await nodeA.start();
await nodeB.start();

// 节点A连接到节点B(服务器作为客户端)
const connection = await nodeA.connectTo(nodeB.getDid());

分阶段连接

const node = new PeerNode(options);

// 方法1:直接start()(推荐)
await node.start();

// 方法2:手动分阶段(高级用法)
await node.connectSignaling();          // 只连接信令服务器
await node.registerToSignaling({        // 注册服务(需要时)
    protocol: "webrtc"
});

环境支持

| 环境 | WebRTC | WebSocket | DRTC | |------|--------|-----------|------| | Node.js | ✅ | ✅ | ✅ | | 浏览器 | ✅ | ✅ | ❌ | | React Native | ✅ | ✅ | ❌ |

浏览器使用

import { PeerNode } from "@lmkdbd/peer-connection/common/browser.js";

React Native 使用

import { PeerNode } from "@lmkdbd/peer-connection/common/react-native.js";

调试

启用调试日志

// 启用WebRTC管理器日志
console.debug = console.log;

// 检查节点状态
console.log("信令连接:", node.webrtcManager.isConnectedToSignaling());
console.log("服务注册:", node.webrtcManager.isRegisteredToSignaling());
console.log("节点DID:", node.getDid());

连接诊断

try {
    const conn = await client.connectTo(serverDid);
    console.log("✅ 连接成功");
} catch (error) {
    if (error.message.includes("Peer not found")) {
        console.log("❌ 目标节点离线或不存在");
    } else if (error.message.includes("not connected")) {
        console.log("❌ 信令服务器连接问题");
    } else {
        console.error("❌ 连接失败:", error.message);
    }
}

常见问题

Q: 如何选择协议?

  • WebRTC: 适用于实时通信,如游戏、视频通话
  • WebSocket: 适用于Web应用,简单易部署
  • DRTC: 适用于高性能数据传输

Q: 信令服务器的作用?

信令服务器用于:

  • 节点发现和注册
  • 协议信息查询
  • WebRTC 连接建立协商

Q: 是否必须启动信令服务器?

  • DID 查询连接:需要
  • 直接 URL 连接:不需要
// 需要信令服务器
await client.connectTo("peer-did-string");

// 不需要信令服务器
await client.connectTo("ws://known-server:8080");

Q: 如何处理连接失败?

// 重试机制
async function connectWithRetry(client, peer_did, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            return await client.connectTo(peer_did);
        } catch (error) {
            if (i === maxRetries - 1) throw error;
            await new Promise(resolve => setTimeout(resolve, 1000));
        }
    }
}

许可证

MIT License

贡献

欢迎提交 Issue 和 Pull Request!

更新日志

v2.0.0

  • ✨ 统一 PeerNode 架构
  • 🔧 WebRTC 管理器分阶段初始化
  • 🚀 服务器双重身份支持
  • ⚡ 按需资源分配优化

v1.0.0

  • 🎉 初始版本
  • 基础的 Client 和 Server 功能