4 个版本

0.2.1 2023 年 5 月 6 日
0.2.0 2023 年 4 月 28 日
0.1.1 2023 年 4 月 15 日
0.1.0 2023 年 4 月 14 日

#5 in #remote-peer

每月 39 次下载

MIT/Apache

68KB
984

preach

平台独立数据通道

Crates.io Docs.rs

Preach 为在原生和网页平台上运行的 WebRTC 数据通道提供抽象。Preach 管理会话描述和 ICE 候选的交换,使通道创建变得简单。此外,Preach 提供简单同步和异步接口以交换消息,使其适用于各种用途。

要创建 WebRTC 连接,必须首先通过信令服务器与远程对等方交换信息。由于信令服务器随用例而变化,Preach 不提供信令服务器实现。然而,Preach 会自动指定应发送给信令服务器的信息。

使用方法

有关完整示例,请参阅 测试

要使用 Preach,必须提供信令服务器实现。这是通过实现 RtcNegotiationHandler 特性来完成的

/// Negotiates a connection with the remote peer during the initial connection process,
/// exchanging messages with the signaling server. 
pub trait RtcNegotiationHandler {
    /// Sends a negotiation message to the remote peer through a signaling implementation.
    fn send(&mut self, message: RtcNegotiationMessage) -> Pin<Box<dyn '_ + Future<Output = Result<(), RtcPeerConnectionError>>>>;
    /// Checks the signaling server for new negotiation messages from the remote peer.
    fn receive(&mut self) -> Pin<Box<dyn '_ + Future<Output = Result<Vec<RtcNegotiationMessage>, RtcPeerConnectionError>>>>;
}

此特性应实现,以便任何从一方发送的消息都可以通过信令服务器被另一方接收。服务器可能以用户希望的方式运行 - 例如,它可以是 REST API 的实现。

提供信令机制后,创建新的一组通道就很容易了

let ice_configuation = IceConfiguration {
    ice_servers: vec!(RtcIceServer { urls: vec!("stun:stun.l.google.com:19302".to_string()), ..Default::default() }),
    ice_transport_policy: RtcIceTransportPolicy::All
};

let negotiation_handler = ...; // Implementation of RtcNegotiationHandler

// Boths peers must use the same set of RtcDataChannelConfigurations for a connection to be created.
let channel = RtcDataChannel::connect(&ice_configuation, negotiation_handler,
    &[RtcDataChannelConfiguration { label: "chan".to_string(), ..Default::default() }]
).await.expect("An error occured during channel creation.")[0];

let msg = b"test msg";

// Send messages.
channel.send(&msg[..]).expect("Could not send message.");

// Receive messages.
assert_eq!(&msg[..], &channel.receive_async().await.expect("An error occurred on the channel.")[..]);

可选特性

vendored - 在桌面平台上静态构建 libdatachannelOpenSSL,并将它们捆绑到构建中。

wasm_main_executor - 允许在 WASM 网页工作者中创建数据通道,并在线程之间共享它们。默认情况下,工作者上的限制阻止它们实例化和处理对等通道。此功能通过将工作推迟到主浏览器线程来绕过这些限制。使用此功能时,必须在创建任何数据通道之前调用 wasm_main_executor::initialize()

依赖关系

~0.6–10MB
~107K SLoC