The PeerConnection class manages a reliable WebRTC data connection to a specific peer. It handles the signaling lifecycle (offers, answers, and ICE candidates) and provides a high-level interface for sending and receiving data.
Key features:
- Automatic Signaling: It uses the provided
MatchmakingClient to exchange WebRTC offers, answers, and ICE candidates. - Reliable Data Channel: It establishes an ordered, reliable
RTCDataChannel for data transmission. - Message Serialization: Data sent via
.send() is automatically encoded using msgpack. Received data is automatically decoded from msgpack. - Event-driven: It emits events like
open and data to notify you of connection state changes and incoming messages.
import { PeerConnection } from "./peerconnection";
// Note: PeerConnection is typically instantiated internally by the MatchmakingClient,
// but its interface is used to interact with peers.
peerConnection.on("open", () => {
console.log("Connected to peer!");
});
peerConnection.on("data", (data) => {
console.log("Received data:", data);
});
peerConnection.send({ type: "chat", text: "hello" });