### Establishing Audio-Only Calls with PeerJS Source: https://context7.com/context7/peerjs/llms.txt Provides examples for establishing audio-only connections using PeerJS. It covers both initiating an audio call and answering an incoming audio call. This is useful for voice chat applications where video is not required. ```javascript navigator.mediaDevices.getUserMedia({ video: false, audio: true }) .then((audioStream) => { const call = peer.call('remote-peer-id', audioStream); call.on('stream', (remoteAudioStream) => { const audio = new Audio(); audio.srcObject = remoteAudioStream; audio.play(); }); }); // Receiving peer peer.on('call', (call) => { navigator.mediaDevices.getUserMedia({ video: false, audio: true }) .then((audioStream) => { call.answer(audioStream); call.on('stream', (remoteAudioStream) => { const audio = new Audio(); audio.srcObject = remoteAudioStream; audio.play(); }); }); }); ``` -------------------------------- ### Initiate Data Connection Source: https://peerjs.com/docs/index Starts a data connection to another peer by calling the `connect` method on the Peer object, providing the destination peer's ID. This returns a DataConnection object. ```javascript var conn = peer.connect('dest-peer-id'); ``` -------------------------------- ### JavaScript PeerJS Video Conference Implementation Source: https://context7.com/context7/peerjs/llms.txt Implements a multi-peer video conference room using PeerJS. It handles getting the local media stream, establishing peer connections, managing incoming and outgoing calls, and dynamically adding/removing video elements for participants. Requires a PeerServer for signaling and TURN servers for NAT traversal in production. ```javascript const peer = new Peer(); const videoCalls = new Map(); let localStream; // Get local video stream navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then((stream) => { localStream = stream; document.getElementById('local-video').srcObject = stream; }); peer.on('open', (myId) => { console.log('Join conference with ID:', myId); }); // Join conference by calling all existing participants function joinConference(participantIds) { participantIds.forEach((participantId) => { if (!videoCalls.has(participantId)) { const call = peer.call(participantId, localStream, { metadata: { username: 'User-' + peer.id.slice(0, 4) } }); call.on('stream', (remoteStream) => { videoCalls.set(participantId, call); addVideoElement(participantId, remoteStream); console.log('Connected to participant:', participantId); }); call.on('close', () => { videoCalls.delete(participantId); removeVideoElement(participantId); }); } }); } // Handle incoming calls peer.on('call', (call) => { console.log('Incoming call from:', call.peer); call.answer(localStream); call.on('stream', (remoteStream) => { videoCalls.set(call.peer, call); addVideoElement(call.peer, remoteStream); }); call.on('close', () => { videoCalls.delete(call.peer); removeVideoElement(call.peer); }); }); function addVideoElement(peerId, stream) { const container = document.getElementById('remote-videos'); const video = document.createElement('video'); video.id = 'video-' + peerId; video.srcObject = stream; video.autoplay = true; video.playsInline = true; container.appendChild(video); } function removeVideoElement(peerId) { const video = document.getElementById('video-' + peerId); if (video) video.remove(); } // Leave conference function leaveConference() { videoCalls.forEach((call) => call.close()); videoCalls.clear(); localStream.getTracks().forEach(track => track.stop()); } ``` -------------------------------- ### Identify Browser Type Source: https://peerjs.com/docs/index Get the name of the current browser. This can be useful for applying browser-specific logic or informing users about compatibility. ```javascript if (util.browser === 'Firefox') { // Special handling for Firefox } ``` -------------------------------- ### Peer Constructor and Options Source: https://peerjs.com/docs/index Initialize a Peer object to connect to other peers. You can provide an ID or let the server generate one. Various options are available to configure the connection, including API keys, host, port, and debugging levels. ```APIDOC ## Peer Constructor ### Description Initializes a Peer object, allowing it to connect to other peers and listen for incoming connections. ### Method `new Peer([id], [options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **id** (string) - Optional - The ID for this peer. If not provided, one will be generated by the brokering server. Must start and end with an alphanumeric character. **options** (object) - Optional - Configuration options for the Peer. - **key** (string) - API key for the cloud PeerServer. Defaults to the key for `0.peerjs.com`. - **host** (string) - Server host. Defaults to `0.peerjs.com`. Accepts `'/'` for relative hostname. - **port** (number) - Server port. Defaults to `443`. - **pingInterval** (number) - Ping interval in ms. Defaults to `5000`. - **path** (string) - The path where your self-hosted PeerServer is running. Defaults to `'/'`. - **secure** (boolean) - `true` if using SSL. Defaults to `false`. - **config** (object) - Configuration hash passed to RTCPeerConnection. Defaults to ICE/TURN server configuration. - **debug** (number) - Debugging level (0: none, 1: errors, 2: errors and warnings, 3: all logs). Defaults to `0`. ### Request Example ```json { "id": "my-peer-id", "options": { "host": "localhost", "port": 9000, "debug": 3 } } ``` ### Response #### Success Response (200) This is a constructor, it returns a Peer object. #### Response Example ```javascript const peer = new Peer('my-peer-id', { host: 'localhost', port: 9000, debug: 3 }); ``` ``` -------------------------------- ### Peer Connection Methods Source: https://peerjs.com/docs/index Methods for initiating connections with remote peers. `peer.connect` establishes a data connection, while `peer.call` initiates a media connection. ```APIDOC ## `peer.connect` ### Description Establishes a data connection to a remote peer. ### Method `peer.connect(id, [options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **id** (string) - Required - The brokering ID of the remote peer. **options** (object) - Optional - Connection options. - **label** (string) - Unique label for the data connection. A random one is generated if not specified. - **metadata** (any) - Metadata associated with the connection. Can be any serializable type. - **serialization** (string) - Serialization format (`binary`, `binary-utf8`, `json`, `none`). Defaults to `binary`. - **reliable** (boolean) - Whether to use reliable data channels. Defaults to `false`. ### Request Example ```json { "id": "remote-peer-id", "options": { "label": "chat-connection", "serialization": "json" } } ``` ### Response #### Success Response (200) Returns a `DataConnection` object. #### Response Example ```javascript const dataConnection = peer.connect('remote-peer-id', { label: 'chat-connection', serialization: 'json' }); ``` --- ## `peer.call` ### Description Initiates a media connection to a remote peer. ### Method `peer.call(id, stream, [options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **id** (string) - Required - The brokering ID of the remote peer. **stream** (MediaStream) - Required - The caller's media stream. **options** (object) - Optional - Connection options. - **metadata** (any) - Metadata associated with the connection. Can be any serializable type. - **sdpTransform** (function) - Function to modify the SDP offer message. ### Request Example ```json { "id": "remote-peer-id", "stream": "", "options": { "metadata": { "username": "Alice" } } } ``` ### Response #### Success Response (200) Returns a `MediaConnection` object. #### Response Example ```javascript const mediaConnection = peer.call('remote-peer-id', myStream, { metadata: { username: 'Alice' } }); ``` ``` -------------------------------- ### Configure Custom PeerServer in JavaScript Source: https://context7.com/context7/peerjs/llms.txt Demonstrates how to configure PeerJS to connect to a self-hosted PeerServer, including specifying host, port, path, and security settings. It also shows how to configure ICE servers (STUN/TURN) for improved connectivity and how to use relative paths for same-origin servers. Debugging levels can also be set. ```javascript // Connect to custom PeerServer const peer = new Peer('custom-peer-id', { host: 'peerserver.example.com', port: 9000, path: '/peerjs', secure: true, config: { iceServers: [ { urls: 'stun:stun.l.google.com:19302' }, { urls: 'stun:stun1.l.google.com:19302' }, { urls: 'turn:turn.example.com:3478', username: 'turnuser', credential: 'turnpassword' } ], iceCandidatePoolSize: 10 }, debug: 2 // Errors and warnings }); // Use relative path for same-origin server const localPeer = new Peer({ host: '/', port: 443, path: '/peerjs', secure: true }); peer.on('open', (id) => { console.log('Connected to custom PeerServer'); }); ``` -------------------------------- ### Initialize Peer Connection (JavaScript) Source: https://peerjs.com/docs/index Creates a new Peer instance. This peer can connect to other peers and listen for incoming connections. An optional ID can be provided, otherwise one will be generated. Various options can be configured for server connection and debugging. ```javascript const peer = new Peer([id], [options]); ``` -------------------------------- ### Establish Data Connections with PeerJS Source: https://context7.com/context7/peerjs/llms.txt Demonstrates establishing bidirectional data connections between peers. The initiating peer connects using a remote peer ID and optional configuration. The receiving peer listens for incoming connections. Both peers handle 'open', 'data', and 'close' events for communication. ```javascript // Initiating peer const conn = peer.connect('remote-peer-id', { label: 'chat-channel', metadata: { username: 'Alice', timestamp: Date.now() }, serialization: 'json', reliable: true }); conn.on('open', () => { console.log('Connection established'); conn.send({ type: 'greeting', message: 'Hello from Alice!' }); }); conn.on('data', (data) => { console.log('Received:', data); }); conn.on('close', () => { console.log('Connection closed'); }); // Receiving peer peer.on('connection', (conn) => { console.log('Incoming connection from:', conn.peer); console.log('Connection metadata:', conn.metadata); conn.on('open', () => { conn.on('data', (data) => { console.log('Received:', data); conn.send({ type: 'response', message: 'Hi ' + conn.metadata.username + '!' }); }); }); }); ``` -------------------------------- ### Managing PeerJS Connection Lifecycle Source: https://context7.com/context7/peerjs/llms.txt Illustrates how to manage the lifecycle of PeerJS connections, including opening, disconnecting, and destroying peers. It demonstrates reconnection logic after a disconnection and proper shutdown procedures. ```javascript const peer = new Peer('my-peer-id'); peer.on('open', (id) => { console.log('Connected to PeerServer with ID:', id); }); peer.on('disconnected', () => { console.log('Disconnected from PeerServer'); console.log('Existing connections remain active:', !peer.disconnected); // Attempt reconnection after 5 seconds setTimeout(() => { if (!peer.destroyed) { peer.reconnect(); console.log('Attempting to reconnect...'); } }, 5000); }); peer.on('close', () => { console.log('Peer closed - no new connections possible'); }); // Manually disconnect (keeps existing connections alive) function disconnect() { peer.disconnect(); } // Clean shutdown function shutdown() { peer.destroy(); // Closes all connections and frees resources console.log('Peer destroyed:', peer.destroyed); } ``` -------------------------------- ### Initialize Peer Connection with PeerJS Source: https://context7.com/context7/peerjs/llms.txt Initializes a PeerJS connection, allowing for automatic ID generation or a custom ID. The 'open' event provides the peer ID, which should be shared for establishing connections. Error handling for the peer connection is also demonstrated. ```javascript const peer = new Peer(); peer.on('open', (id) => { console.log('My peer ID is:', id); }); const customPeer = new Peer('my-unique-peer-id', { host: 'localhost', port: 9000, path: '/myapp', secure: true, config: { iceServers: [ { urls: 'stun:stun.l.google.com:19302' }, { urls: 'turn:turn.example.com:3478', username: 'user', credential: 'pass' } ], sdpSemantics: 'unified-plan' }, debug: 3 }); customPeer.on('error', (err) => { console.error('Peer error:', err.type, err.message); }); ``` -------------------------------- ### Listen for Peer Events (JavaScript) Source: https://peerjs.com/docs/index Sets up event listeners for various PeerJS events. This includes 'open' for server connection, 'connection' for incoming data connections, 'call' for incoming media calls, 'close' when the peer is destroyed, and 'disconnected' when the peer loses its connection to the server. ```javascript peer.on(event, callback); ``` ```javascript peer.on('open', function(id) { ... }); ``` ```javascript peer.on('connection', function(dataConnection) { ... }); ``` ```javascript peer.on('call', function(mediaConnection) { ... }); ``` ```javascript peer.on('close', function() { ... }); ``` ```javascript peer.on('disconnected', function() { ... }); ``` -------------------------------- ### Create Peer Object Initialization Source: https://peerjs.com/docs/index Initializes a new Peer object, which is central to creating and receiving peer connections. PeerJS uses PeerServer for signaling. You can optionally provide your own IDs. ```javascript var peer = new Peer(); ``` -------------------------------- ### Answering Incoming Media Calls with PeerJS Source: https://context7.com/context7/peerjs/llms.txt Demonstrates how to receive and answer incoming media calls using PeerJS. It includes obtaining the local media stream and handling remote streams. The snippet also shows how to answer a call without sending your own stream, making it a one-way call. ```javascript let localStream; // Get local media stream navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then((stream) => { localStream = stream; const localVideo = document.getElementById('local-video'); localVideo.srcObject = localStream; }); peer.on('call', (call) => { console.log('Incoming call from:', call.peer); console.log('Call metadata:', call.metadata); // Answer with local stream call.answer(localStream); call.on('stream', (remoteStream) => { const remoteVideo = document.getElementById('remote-video'); remoteVideo.srcObject = remoteStream; console.log('Receiving remote stream'); }); call.on('close', () => { console.log('Call closed'); }); // One-way call: answer without sending own stream // call.answer(); // Remote peer sends video, you only receive }); ``` -------------------------------- ### Make Video/Audio Calls with PeerJS Source: https://context7.com/context7/peerjs/llms.txt Enables real-time audio and video communication using PeerJS. It utilizes `navigator.mediaDevices.getUserMedia` to access the local media stream, displays it, and then establishes a media call to a remote peer. The remote stream is then displayed, and call events like 'close' and 'error' are handled. ```javascript navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then((localStream) => { const localVideo = document.getElementById('local-video'); localVideo.srcObject = localStream; const call = peer.call('remote-peer-id', localStream, { metadata: { caller: 'Alice', callType: 'video' } }); call.on('stream', (remoteStream) => { const remoteVideo = document.getElementById('remote-video'); remoteVideo.srcObject = remoteStream; }); call.on('close', () => { console.log('Call ended'); remoteVideo.srcObject = null; }); call.on('error', (err) => { console.error('Call error:', err); }); }) .catch((err) => { console.error('Media access denied:', err); }); ``` -------------------------------- ### Establish Media Connection (JavaScript) Source: https://peerjs.com/docs/index Initiates a media connection (for audio/video) to a remote peer. This requires the remote peer's ID and the caller's media stream. It returns a MediaConnection object, and errors should be handled via the 'error' event. ```javascript const mediaConnection = peer.call(id, stream, [options]); ``` -------------------------------- ### PeerJS DataConnection Properties and Methods Source: https://context7.com/context7/peerjs/llms.txt Explains how to utilize DataConnection properties and methods in PeerJS for advanced data transfer. It covers connection configuration options, accessing underlying WebRTC objects, sending data, and closing the connection. ```javascript const conn = peer.connect('remote-peer-id', { label: 'game-data', serialization: 'binary', reliable: false // Unreliable for real-time gaming }); conn.on('open', () => { console.log('Connection open:', conn.open); console.log('Peer ID:', conn.peer); console.log('Connection type:', conn.type); // 'data' console.log('Label:', conn.label); console.log('Serialization:', conn.serialization); console.log('Reliable:', conn.reliable); console.log('Buffer size:', conn.bufferSize); // Access underlying WebRTC objects const rtcDataChannel = conn.dataChannel; const rtcPeerConnection = conn.peerConnection; console.log('DataChannel state:', rtcDataChannel.readyState); console.log('ICE connection state:', rtcPeerConnection.iceConnectionState); // Send data conn.send({ x: 100, y: 200, action: 'move' }); // Close when done conn.close(); }); ``` -------------------------------- ### Include PeerJS Client Library Source: https://peerjs.com/docs/index This snippet shows how to include the PeerJS Javascript client library in your HTML file using a CDN link. Alternatively, you can host the 'peerjs.min.js' file locally. ```html ``` -------------------------------- ### Initiate Video/Audio Call Source: https://peerjs.com/docs/index Initiates a video or audio call to another peer using the `peer.call` method, providing the destination peer's ID and the local `mediaStream`. This returns a MediaConnection object. ```javascript // Call a peer, providing our mediaStream var call = peer.call('dest-peer-id', mediaStream); ``` -------------------------------- ### Peer Event Listeners Source: https://peerjs.com/docs/index Set up listeners for various Peer events to handle incoming connections, calls, and connection status changes. ```APIDOC ## `peer.on` ### Description Sets up listeners for Peer events. ### Method `peer.on(event, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body **event** (string) - The name of the event to listen for. - `'open'`: Emitted when a connection to the PeerServer is established. The `id` of the peer is provided. - `'connection'`: Emitted when a new data connection is established from a remote peer. A `DataConnection` object is provided. - `'call'`: Emitted when a remote peer attempts to call. A `MediaConnection` object is provided. You must call `mediaConnection.answer([stream])` to accept. - `'close'`: Emitted when the peer is destroyed and can no longer accept or create connections. - `'disconnected'`: Emitted when the peer's connection to the PeerServer is lost. **callback** (function) - The function to execute when the event is triggered. ### Request Example ```javascript peer.on('open', function(id) { console.log('My peer ID is: ' + id); }); peer.on('connection', function(dataConnection) { console.log('Incoming data connection:', dataConnection.label); }); peer.on('call', function(mediaConnection) { console.log('Incoming call:', mediaConnection.metadata); mediaConnection.answer(myStream); }); ``` ### Response #### Success Response (200) No direct response, but the callback function will be executed when the specified event occurs. #### Response Example See Request Example. ``` -------------------------------- ### Establish Data Connection (JavaScript) Source: https://peerjs.com/docs/index Initiates a data connection to a remote peer specified by their ID. This method returns a DataConnection object. It's crucial to handle potential connection errors by listening to the 'error' event on the returned connection. ```javascript const dataConnection = peer.connect(id, [options]); ``` -------------------------------- ### Manage Media Connections and Streams in JavaScript Source: https://context7.com/context7/peerjs/llms.txt Initiates a media call to a remote peer, handles incoming media streams, and provides options for stream manipulation like muting audio tracks. It also includes logic for automatically closing the call after a specified duration. No external dependencies are strictly required beyond a browser environment supporting WebRTC. ```javascript const call = peer.call('remote-peer-id', localStream, { metadata: { roomId: 'room-123' } }); call.on('stream', (remoteStream) => { console.log('Call answered:', call.open); console.log('Remote peer:', call.peer); console.log('Connection type:', call.type); // 'media' console.log('Metadata:', call.metadata); // Get stream tracks const audioTracks = remoteStream.getAudioTracks(); const videoTracks = remoteStream.getVideoTracks(); console.log('Audio tracks:', audioTracks.length); console.log('Video tracks:', videoTracks.length); // Mute/unmute audioTracks.forEach(track => track.enabled = false); // Mute // End call setTimeout(() => { call.close(); }, 60000); // 1 minute call }); ``` -------------------------------- ### Check Browser Compatibility Source: https://peerjs.com/docs/index Determine if the current browser supports necessary WebRTC features for data and media connections. This check is vital for progressive enhancement and user experience. ```javascript if (util.supports.audioVideo) { console.log('Browser supports audio/video.'); } if (util.supports.data) { console.log('Browser supports data channels.'); } ``` -------------------------------- ### Configure Peer with TURN Server Source: https://peerjs.com/docs/index Configures the Peer object to use a TURN server for NAT traversal. This is done by passing an 'iceServers' array within the 'config' option when creating the Peer object. This enhances connectivity for users behind restrictive NATs. ```javascript var peer = new Peer({ config: {'iceServers': [ { url: 'stun:stun.l.google.com:19302' }, { url: 'turn:homeo@turn.bistri.com:80', credential: 'homeo' } ]} /* Sample servers, please use appropriate ones */ }); ``` -------------------------------- ### Implement PeerJS Real-Time Game State Synchronization Source: https://context7.com/context7/peerjs/llms.txt Synchronizes game state between peers with low latency using PeerJS's unreliable data channels. It sends player positions at approximately 60 FPS and updates the game state on the receiving end, triggering a re-render. ```javascript // Game peer setup const peer = new Peer(); let gameState = { players: {} }; peer.on('open', (id) => { document.getElementById('peer-id').textContent = id; }); // Connect to opponent function connectToOpponent(opponentId) { const conn = peer.connect(opponentId, { label: 'game-state', serialization: 'json', reliable: false // Low latency for real-time gaming }); conn.on('open', () => { console.log('Game connection established'); // Send local player position every frame setInterval(() => { conn.send({ type: 'position', playerId: peer.id, x: gameState.players[peer.id]?.x || 0, y: gameState.players[peer.id]?.y || 0, timestamp: Date.now() }); }, 16); // ~60 FPS }); conn.on('data', (data) => { if (data.type === 'position') { // Update opponent position gameState.players[data.playerId] = { x: data.x, y: data.y, timestamp: data.timestamp }; renderGame(); } }); } // Handle incoming game connections peer.on('connection', (conn) => { if (conn.label === 'game-state') { conn.on('data', (data) => { if (data.type === 'position') { gameState.players[data.playerId] = { x: data.x, y: data.y, timestamp: data.timestamp }; renderGame(); } }); } }); function renderGame() { // Render all players Object.entries(gameState.players).forEach(([playerId, player]) => { console.log('Player', playerId, 'at', player.x, player.y); }); } ``` -------------------------------- ### Manage Multiple Peer Connections in JavaScript Source: https://context7.com/context7/peerjs/llms.txt Provides a pattern for managing multiple simultaneous peer connections in a mesh network using a `Map` to track active connections. It includes functions to connect to new peers, handle incoming connections, send data to specific peers or broadcast to all, and manage connection lifecycle events like 'open' and 'close'. ```javascript const peer = new Peer(); const connections = new Map(); // Track connections manually peer.on('open', (myId) => { console.log('My ID:', myId); }); // Connect to multiple peers function connectToPeer(peerId) { if (connections.has(peerId)) { console.log('Already connected to', peerId); return; } const conn = peer.connect(peerId, { metadata: { timestamp: Date.now() } }); conn.on('open', () => { connections.set(peerId, conn); console.log('Connected to', peerId, '- Total connections:', connections.size); conn.send({ type: 'hello', from: peer.id }); }); conn.on('data', (data) => { console.log('From', peerId, ':', data); }); conn.on('close', () => { connections.delete(peerId); console.log('Disconnected from', peerId); }); } // Handle incoming connections peer.on('connection', (conn) => { conn.on('open', () => { connections.set(conn.peer, conn); console.log('Incoming connection from', conn.peer); }); conn.on('data', (data) => { console.log('From', conn.peer, ':', data); }); conn.on('close', () => { connections.delete(conn.peer); }); }); // Broadcast to all connected peers function broadcast(message) { connections.forEach((conn, peerId) => { if (conn.open) { conn.send(message); } }); console.log('Broadcasted to', connections.size, 'peers'); } // Connect to multiple peers connectToPeer('peer-1'); connectToPeer('peer-2'); connectToPeer('peer-3'); // Later: broadcast a message setTimeout(() => { broadcast({ type: 'announcement', text: 'Hello everyone!' }); }, 5000); ``` -------------------------------- ### Listen for Data on DataConnection Source: https://peerjs.com/docs/index Sets up a listener for the 'data' event on a `DataConnection`. This callback function is executed whenever data is received from the remote peer. The received data is passed as an argument to the callback. ```javascript dataConnection.on('data', function(data) { console.log('Received data:', data); }); ``` -------------------------------- ### PeerJS Error Handling Source: https://context7.com/context7/peerjs/llms.txt Details how to handle various error types that can occur with PeerJS connections. It includes specific error codes like 'browser-incompatible', 'invalid-id', and 'network' errors, along with general error handling for connections. ```javascript peer.on('error', (err) => { switch(err.type) { case 'browser-incompatible': console.error('Browser does not support WebRTC'); alert('Please use a modern browser'); break; case 'invalid-id': console.error('Invalid peer ID:', err.message); break; case 'invalid-key': console.error('Invalid API key'); break; case 'network': console.error('Network error - cannot reach PeerServer'); // Retry logic break; case 'peer-unavailable': console.error('Target peer does not exist or is offline'); break; case 'ssl-unavailable': console.error('SSL not supported by cloud server'); break; case 'unavailable-id': console.error('Peer ID already taken'); // Generate new ID break; case 'webrtc': console.error('WebRTC error:', err.message); break; default: console.error('Unknown error:', err); } }); // Connection-specific error handling const conn = peer.connect('target-peer-id'); conn.on('error', (err) => { console.error('Connection error:', err); }); ``` -------------------------------- ### Answer Incoming Video/Audio Call Source: https://peerjs.com/docs/index Handles incoming call requests by listening for the 'call' event on the Peer object. The call is answered using `call.answer`, optionally providing the local `mediaStream`. ```javascript peer.on('call', function(call) { // Answer the call, providing our mediaStream call.answer(mediaStream); }); ``` -------------------------------- ### Implement PeerJS File Transfer with Binary Serialization Source: https://context7.com/context7/peerjs/llms.txt Transfers files between peers using PeerJS, supporting large files through binary serialization and chunking. It first sends file metadata (name, size, mimeType) and then the file data as an ArrayBuffer. The receiver reconstructs the file and prompts a download. ```javascript // Sender const conn = peer.connect('receiver-peer-id', { serialization: 'binary', reliable: true }); function sendFile(file) { conn.on('open', () => { // Send file metadata first conn.send({ type: 'file-info', name: file.name, size: file.size, mimeType: file.type }); // Send file data const reader = new FileReader(); reader.onload = (e) => { conn.send({ type: 'file-data', data: e.target.result }); console.log('File sent:', file.name, file.size, 'bytes'); }; reader.readAsArrayBuffer(file); }); } const fileInput = document.getElementById('file-input'); fileInput.addEventListener('change', (e) => { const file = e.target.files[0]; sendFile(file); }); // Receiver let receivedFileInfo = null; let receivedFileData = null; peer.on('connection', (conn) => { conn.on('data', (data) => { if (data.type === 'file-info') { receivedFileInfo = data; console.log('Receiving file:', data.name, data.size, 'bytes'); } else if (data.type === 'file-data') { receivedFileData = data.data; // Create download link const blob = new Blob([receivedFileData], { type: receivedFileInfo.mimeType }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = receivedFileInfo.name; a.click(); console.log('File received and downloaded'); } }); }); ``` -------------------------------- ### Handle Peer Open Event Source: https://peerjs.com/docs/index Listens for the 'open' event on the Peer object, which is triggered when the Peer object is ready and has been assigned a unique ID. This ID is crucial for other peers to connect to this instance. ```javascript peer.on('open', function(id) { console.log('My peer ID is: ' + id); }); ``` -------------------------------- ### Handle DataConnection Open Event Source: https://peerjs.com/docs/index Listens for the 'open' event on a `DataConnection`. This event signifies that the data connection has been successfully established and is ready for read and write operations. It's typically used to initiate data transfer once the connection is confirmed. ```javascript dataConnection.on('open', function() { console.log('Data connection is open'); }); ``` -------------------------------- ### Browser and WebRTC Feature Detection in JavaScript Source: https://context7.com/context7/peerjs/llms.txt Checks browser compatibility and specific WebRTC feature support (data, audio/video, binary, reliable channels) using the `util` object. This helps in conditionally executing code based on browser capabilities, preventing errors in unsupported environments. It logs browser information and feature support to the console. ```javascript // Check browser type console.log('Current browser:', util.browser); // Output: 'chrome', 'firefox', 'safari', 'edge', 'Not a supported browser.', etc. // Check WebRTC feature support if (util.supports.data) { console.log('Data connections supported'); const conn = peer.connect('target-peer-id'); } else { console.error('Data connections not supported in this browser'); } if (util.supports.audioVideo) { console.log('Media connections supported'); navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then((stream) => { const call = peer.call('target-peer-id', stream); }); } else { console.error('Media connections not supported'); } if (util.supports.binary) { console.log('Binary data channels supported'); } if (util.supports.reliable) { console.log('Reliable data channels supported'); } // Conditional features based on browser if (util.browser === 'firefox') { console.log('Firefox-specific optimizations enabled'); } else if (util.browser === 'chrome') { console.log('Chrome-specific features available'); } ``` -------------------------------- ### Answer Media Connection Source: https://peerjs.com/docs/index Accept an incoming media call and optionally provide your own media stream. This method is crucial for establishing two-way audio/video communication. ```javascript mediaConnection.answer(stream, { sdpTransform: myTransform }); ``` -------------------------------- ### Peer Destroy Method Source: https://peerjs.com/docs/index Closes all connections, including the server connection and all existing data/media connections. Sets `peer.destroyed` to true. ```APIDOC ## Destroy Peer Instance ### Description Close the connection to the server and terminate all existing connections. `peer.destroyed` will be set to `true`. This cannot be undone; the respective peer object will no longer be able to create or receive any connections, its ID will be forfeited on the (cloud) server, and all of its data and media connections will be closed. ### Method `peer.destroy()` ### Example ```javascript peer.destroy(); ``` ``` -------------------------------- ### DataConnection Send Method Source: https://peerjs.com/docs/index Sends data to the remote peer over an established DataConnection. Data is serialized using BinaryPack by default. ```APIDOC ## Send Data ### Description Sends data to the remote peer. The `data` can be any serializable type, including objects, strings, and blobs. ### Method `dataConnection.send(data)` ### Parameters - `data` (any) - The data to send. ### Example ```javascript // Assuming dataConnection is an established DataConnection object dataConnection.send({ message: 'Hello!' }); ``` ``` -------------------------------- ### Handle Remote Stream Source: https://peerjs.com/docs/index Listen for the 'stream' event on a MediaConnection to receive and play the remote peer's media stream. This is fundamental for displaying video or audio from the connected peer. ```javascript mediaConnection.on('stream', function(stream) { // Play the remote stream }); ``` -------------------------------- ### Manage DataConnection Events and Data Transfer Source: https://peerjs.com/docs/index Handles 'open' and 'data' events for a DataConnection object. It allows receiving data sent from the remote peer and sending data to it. Supports various data types including JSON, Blobs, and ArrayBuffers. ```javascript conn.on('open', function() { // Receive messages conn.on('data', function(data) { console.log('Received', data); }); // Send messages conn.send('Hello!'); }); ``` -------------------------------- ### Send Complex Data Types over PeerJS Source: https://context7.com/context7/peerjs/llms.txt Illustrates sending various complex data types, including nested objects, Blobs, and ArrayBuffers, over a PeerJS data connection. It also shows how to handle file uploads by sending a File object as a Blob. ```javascript const conn = peer.connect('target-peer-id'); conn.on('open', () => { conn.send({ strings: 'Hello World', numbers: 12345, arrays: [1, 2, 3, 4, 5], nested: { bool: true, float: 3.14159, nullValue: null }, binary: new Blob(['Binary content'], { type: 'text/plain' }), buffer: new ArrayBuffer(8) }); const fileInput = document.querySelector('input[type="file"]'); fileInput.addEventListener('change', (e) => { const file = e.target.files[0]; conn.send({ type: 'file', filename: file.name, data: file }); }); }); ``` -------------------------------- ### Peer Error Event Source: https://peerjs.com/docs/index Handles errors that occur within the PeerJS instance. These errors are often fatal and can lead to the destruction of the peer object. ```APIDOC ## Peer Error Handling ### Description Errors on the peer are almost always fatal and will destroy the peer. Errors from the underlying socket and PeerConnections are forwarded here. ### Event `error` ### Callback `function(err)` ### Error Types - `browser-incompatible`: The client's browser does not support some or all WebRTC features. - `disconnected`: The peer has already been disconnected from the server. - `invalid-id`: The ID passed into the Peer constructor contains illegal characters. - `invalid-key`: The API key passed into the Peer constructor is invalid or not in the system. - `network`: Lost or cannot establish a connection to the signalling server. - `peer-unavailable`: The peer you're trying to connect to does not exist. - `ssl-unavailable`: PeerJS is being used securely, but the cloud server does not support SSL. - `server-error`: Unable to reach the server. - `socket-error`: An error from the underlying socket. - `socket-closed`: The underlying socket closed unexpectedly. - `unavailable-id`: The ID passed into the Peer constructor is already taken (sometimes fatal). - `webrtc`: Native WebRTC errors. ### Example ```javascript peer.on('error', (err) => { console.error('An error occurred:', err.type, err.message); }); ``` ``` -------------------------------- ### DataConnection Event Listener Source: https://peerjs.com/docs/index Attaches event listeners to a DataConnection to handle incoming data, connection status changes, and errors. ```APIDOC ## DataConnection Event Listeners ### Description Set listeners for data connection events to handle various states and data exchanges. ### Method `dataConnection.on(event, callback)` ### Events - `data`: Emitted when data is received from the remote peer. Callback receives `data`. - `open`: Emitted when the connection is established and ready for use. - `close`: Emitted when either you or the remote peer closes the data connection. - `error`: Emitted when an error occurs on the data connection. Callback receives `err`. ### Example ```javascript // Assuming dataConnection is an established DataConnection object dataConnection.on('data', (data) => { console.log('Received data:', data); }); dataConnection.on('open', () => { console.log('Data connection is open'); }); dataConnection.on('close', () => { console.log('Data connection closed'); }); dataConnection.on('error', (err) => { console.error('Data connection error:', err); }); ``` ``` -------------------------------- ### Receive Data Connection Event Source: https://peerjs.com/docs/index Listens for incoming connection requests from other peers. When another peer attempts to connect, the 'connection' event is emitted, providing a DataConnection object. ```javascript peer.on('connection', function(conn) { ... }); ``` -------------------------------- ### Handle DataConnection Close Event Source: https://peerjs.com/docs/index Sets up a listener for the 'close' event on a `DataConnection`. This event is triggered when either the local or remote peer closes the data connection, indicating that communication on this channel has ended. ```javascript dataConnection.on('close', function() { console.log('Data connection closed'); }); ``` -------------------------------- ### Handle Peer Error Events Source: https://peerjs.com/docs/index Listens for the 'error' event on a peer. This event captures various errors, most of which are fatal and will destroy the peer. It's crucial for diagnosing connection issues and understanding the state of the peer. ```javascript peer.on('error', function(err) { console.error('Peer error:', err); }); ``` -------------------------------- ### Reconnect Peer to Server Source: https://peerjs.com/docs/index Attempts to re-establish a connection to the signalling server using the `reconnect()` method. This is only possible for peers that have been disconnected. If the reconnection fails (e.g., ID is taken), relevant error events will fire. ```javascript peer.reconnect(); ``` -------------------------------- ### Peer Reconnect Method Source: https://peerjs.com/docs/index Attempts to re-establish connection to the PeerServer using the peer's previous ID. Only applicable for disconnected peers. ```APIDOC ## Reconnect to Server ### Description Attempt to reconnect to the server with the peer's old ID. Only disconnected peers can be reconnected. Destroyed peers cannot be reconnected. If the connection fails, the peer's existing connections will not close, but any associated errors events will fire. ### Method `peer.reconnect()` ### Example ```javascript peer.reconnect(); ``` ``` -------------------------------- ### Send Data Over DataConnection Source: https://peerjs.com/docs/index Sends data to a remote peer using the `send()` method of a `DataConnection`. The data is automatically serialized using BinaryPack by default and can be of various types, including objects, strings, and blobs. ```javascript dataConnection.send(dataToSend); ``` -------------------------------- ### Send Complex Data Types via DataConnection Source: https://peerjs.com/docs/index Demonstrates sending complex data structures, including nested objects, arrays, Blobs, and booleans, through a PeerJS data connection. PeerJS handles the serialization using BinaryPack. ```javascript conn.send({ strings: 'hi!', numbers: 150, arrays: [1,2,3], evenBinary: new Blob([1,2,3]), andMore: {bool: true} }); ``` -------------------------------- ### Destroy Peer and Connections Source: https://peerjs.com/docs/index Terminates all connections and closes the connection to the signalling server using the `destroy()` method. This action sets the `destroyed` property to `true`, forfeits the peer's ID, and closes all associated data and media channels. ```javascript peer.destroy(); ``` -------------------------------- ### Peer Disconnect Method Source: https://peerjs.com/docs/index Closes the connection to the PeerServer, leaving existing data and media connections intact. Sets `peer.disconnected` to true. ```APIDOC ## Disconnect from Server ### Description Close the connection to the server, leaving all existing data and media connections intact. `peer.disconnected` will be set to `true` and the `disconnected` event will fire. This cannot be undone; the respective peer object will no longer be able to create or receive any connections and its ID will be forfeited on the (cloud) server. ### Method `peer.disconnect()` ### Example ```javascript peer.disconnect(); ``` ``` -------------------------------- ### DataConnection Close Method Source: https://peerjs.com/docs/index Gracefully closes the data connection, releasing underlying resources like DataChannels and PeerConnections. ```APIDOC ## Close Data Connection ### Description Closes the data connection gracefully, cleaning up underlying DataChannels and PeerConnections. ### Method `dataConnection.close()` ### Example ```javascript // Assuming dataConnection is an established DataConnection object dataConnection.close(); ``` ``` -------------------------------- ### Handle Remote MediaStream in Call Source: https://peerjs.com/docs/index Listens for the 'stream' event on a MediaConnection object. This event is triggered when the remote peer's audio or video stream becomes available. The received MediaStream can then be attached to HTML media elements. ```javascript call.on('stream', function(stream) { // `stream` is the MediaStream of the remote peer. // Here you'd add it to an HTML video/canvas element. }); ``` -------------------------------- ### Handle DataConnection Error Event Source: https://peerjs.com/docs/index Listens for the 'error' event on a `DataConnection`. This callback is invoked when an error occurs during the data connection lifecycle. It's essential for monitoring and debugging connection problems. ```javascript dataConnection.on('error', function(err) { console.error('Data connection error:', err); }); ```