This is a simple peer-to-peer library for Rust + WASM, built on top of WebRTC.
- 🪶 Lightweight
- 🤝 User-friendly
- 🚀 Blazing fast
🏗️ Ideal for:
- 🌐 Decentralized apps
- 👥 Real-time collaboration
- 🎮 Browser-based games
In the following example, we will connect to another peer and send it Hello world
:
use wasm_p2p::{wasm_bindgen_futures, P2P};
fn main() {
wasm_bindgen_futures::spawn_local(main_async());
}
async fn main_async() {
let p2p = P2P::new("wss://signaling.luisherasme.com").await;
let peer = p2p.connect("other-peer-id").await;
peer.send("Hello world");
}
cargo add wasm_p2p
To establish a peer-to-peer connection, we need to send information like our IP address to the other peer so that it knows how to reach us. The server that we use to exchange this information is called a signaling server.
To initialize the P2P
client, you need to pass the URL of the signaling server:
let mut p2p = P2P::new("wss://signaling.luisherasme.com").await;
In the previous example, we used wss://signaling.luisherasme.com
as the signaling server. This server is free, and the code is open source so that you can create your own version. The code is available here.
The signaling server assigns a random, unique ID to each peer:
let id = p2p.id();
You can start a connection by calling p2p.connect
with the peer ID of the destination peer.
let connection = p2p.connect("OTHER_PEER_ID").await;
You can get all the new connections by calling p2p.receive_connections
:
let connections = p2p.receive_connections();
To receive messages from the other peers that are connected to you, you can call the receive
method:
let messages = connection.receive();
To send a message to another peer you have to use the send
method:
let data = "EXAMPLE DATA YOU CAN SEND ANY &STR";
peer.send(data);
You can set your own ICE servers:
use wasm_p2p::{wasm_bindgen_futures, ConnectionUpdate, P2P, IceServer};
fn main() {
wasm_bindgen_futures::spawn_local(main_async());
}
async fn main_async() {
let mut p2p = P2P::new("wss://signaling.luisherasme.com");
let ice_servers = vec![IceServer {
urls: String::from("stun:stun.l.google.com:19302"),
credential: None,
credential_type: None,
username: None,
}];
p2p.set_ice_servers(ice_servers);
}
Furthermore, you can create an ICE server from a &str
:
use wasm_p2p::{wasm_bindgen_futures, ConnectionUpdate, P2P, IceServer};
fn main() {
wasm_bindgen_futures::spawn_local(main_async());
}
async fn main_async() {
let mut p2p = P2P::new("wss://signaling.luisherasme.com");
let ice_servers = vec![IceServer::from("stun:stun.l.google.com:19302")];
p2p.set_ice_servers(ice_servers);
}
- P2P chat. Demo, Repository.