Peer Connections
The Peer class provides methods for joining and leaving rooms, publishing and subscribing to media streams, opening and closing data channels, and handling various events related to peer connections. The library will automatically manage the underlying
WebRTC
connections, including peer discovery, connection negotiation, media stream handling, and data channel communication. You can focus on building your application logic while
Peerix
takes care of the complexities of WebRTC.
Creating Peer Instance
The Peer class is the core of the library. It manages peer connections, media streams, and data channels. You can create an instance of Peer by providing a signaling driver and optional configuration parameters:
import { Peer, BroadcastChannelDriver } from 'peerix';
// create the specific driver instance
const driver = new BroadcastChannelDriver('my-app-channel');
// create the Peer instance with the driver
const peer = new Peer({ driver });Important
You should choose the signaling driver that best fits your application’s needs.
Peerix provides several built-in drivers, such as the Memory Driver for testing and development, the BroadcastChannel Driver for communication between tabs in the same browser, and the NATS Driver for communication between peers across different browsers and devices. You can also implement your own custom signaling driver if needed.
For
NAT
traversal, you should use a
STUN
server, for example stun.l.google.com:19302 for free. However, for better connectivity, especially in restrictive network environments, it is recommended to use a
TURN
server. You should specify TURN/STUN servers in the iceServers configuration option:
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{
urls: 'turn:turn.example.com:3478',
username: 'user',
credential: 'pass'
}
]Tip
Use TURN servers for production applications.
For production applications, it is highly recommended to set up your own TURN server or use a reliable TURN service provider to ensure better connectivity and performance for your users. Relying on public STUN servers may lead to connectivity issues, especially in restrictive network environments where TURN servers are required for successful peer-to-peer connections.
Connection Management
Peerix will automatically handle peer discovery, connection management, media streams and data channels negotiation. To join a room and start sharing media streams or sending messages, simply call the join method with the desired room ID:
// listen for peer joining the room
peer.on('connection', (e) => {
const { remote, state } = e;
console.log(`Peer: ${remote.id}, State: ${state}`);
});
// listen for connection errors
peer.on('error', (e) => {
const { error } = e;
console.error('Error:', error);
});
// join a room
peer.join({
room: 'room-id',
metadata: { /* optional metadata */ }
});
// later, if you want to leave the room
peer.leave();Optionally, you can provide metadata with the join method that will be shared with other peers in the room. This can include information such as the peer’s name or any other relevant data.
When you call the join method, Peerix will use the provided signaling driver to discover other peers in the specified room and establish peer-to-peer connections with them. The library will automatically handle the negotiation of media streams and data channels between connected peers, allowing you to focus on building your application logic without worrying about the underlying WebRTC complexities.
Peerix establishes a peer connection with a negotiated data channel for signaling after the initial connection is established, eliminating the need for a signaling server during the lifetime of the peer connection. This design allows for efficient communication between peers while minimizing signaling overhead and improving performance. So, even you do not share media streams or open data channels, the library will still establish a peer connection and wait for you to publish media streams or open data channels to start sharing with other peers in the room. This allows for a more flexible and dynamic communication experience, as peers can join a room and establish connections without needing to immediately share media or data, while still being ready to do so when needed.
sequenceDiagram
autonumber
Note over Peer1,Peer2: Join the same room
Peer2->>Peer1: signaling broadcast: join
Peer1->>Peer1: Peer Connection +<br>Signaling Data Channel
Peer1->>Peer2: signaling: offer
Peer2->>Peer2: Peer Connection +<br>Signaling Data Channel
Peer2->>Peer1: signaling: answer
Note over Peer1,Peer2: Connection established
Tip
Use one connection per peer to share multiple media streams and data channels in both directions for better performance and resource usage.
Peerix allows you to use a single connection with each other peer in the room to share multiple media streams and data channels in two directions. This means that you can publish multiple media streams and open multiple data channels with the same peer without needing to establish separate connections for each stream or channel. The library will manage the negotiation and sharing of all streams and channels over the single connection, optimizing the communication between peers and reducing load on client resources, signaling, and STUN/TURN servers.
Lifecycle Events
Peerix uses an event-driven architecture that allows you to listen for and handle various events related to peer connections, media streams, and data channels. This design makes it easier to manage peer interactions and build real-time applications. You can listen for events such as when a peer joins or leaves a room, when a media stream is added or removed, when a data channel is opened or receives a message, and many more.
Lifecycle events include:
connection[:new,:connecting,:connected,:disconnected,:failed,:closed]: a peer’s connection state changes.channel[:new,:open,:close,:message,:error]: a data channel’s state changes or it receives a message.stream[:add,:remove]: a remote peer publishes or unpublishes a media stream.track[:add,:remove]: a track is added or removed from a media stream by a remote peer.error: an error occurs with a peer connection, media stream, data channel, or signaling.
You can subscribe to either group or specific events using the :event suffix.