📅  最后修改于: 2023-12-03 15:18:17.480000             🧑  作者: Mango
PeerJS is a simple yet powerful JavaScript library that enables peer-to-peer communication between browsers or nodes. It eliminates the need for a server to facilitate communication between two or more clients, making communication faster and more efficient.
PeerJS can be easily installed using NPM or included as a script in your HTML file.
npm install peer
<script src="https://cdn.peerjs.com/peerjs.min.js"></script>
To use PeerJS, you need to create a Peer instance in your application.
const peer = new Peer();
Once you have a Peer instance, you can connect to other peers using their ID.
const conn = peer.connect('some-other-peer-id');
You can also receive connections from other peers using the on
method.
peer.on('connection', (conn) => {
// Handle incoming connection
});
To exchange data with other peers, you can use the send
method on the connection object.
conn.send('Hello World!');
PeerJS comes with advanced features such as multiparty communication, binary data transfer, and more. Here is an example of how to use multiparty communication.
const room = peer.joinRoom('my-room-name');
room.on('open', () => {
console.log('Room opened');
});
room.on('peerJoin', (peer) => {
console.log('Peer joined:', peer);
});
room.on('peerLeave', (peer) => {
console.log('Peer left:', peer);
});
room.on('data', (data) => {
console.log('Data received:', data);
});
room.send('Hello World!');
PeerJS is a powerful library that enables peer-to-peer communication in the browser or NodeJS environment. It's easy to set up, fully open-source, and comes with advanced features to handle complex use cases. Whether you're building a real-time chat application or a multiplayer game, PeerJS can help you achieve your goals.