Giter Club home page Giter Club logo

peerjs's Introduction

PeerJS: Simple peer-to-peer with WebRTC

Backers on Open Collective Sponsors on Open Collective Discord

PeerJS provides a complete, configurable, and easy-to-use peer-to-peer API built on top of WebRTC, supporting both data channels and media streams.

Live Example

Here's an example application that uses both media and data connections: https://glitch.com/~peerjs-video. The example also uses its own PeerServer.


Special Announcement:

We now have a Discord Channel
There we plan to discuss roadmaps, feature requests, and more
Join us today


Setup

Include the library

with npm: npm install peerjs

with yarn: yarn add peerjs

// The usage -
import { Peer } from "peerjs";

Create a Peer

const peer = new Peer("pick-an-id");
// You can pick your own id or omit the id if you want to get a random one from the server.

Data connections

Connect

const conn = peer.connect("another-peers-id");
conn.on("open", () => {
	conn.send("hi!");
});

Receive

peer.on("connection", (conn) => {
	conn.on("data", (data) => {
		// Will print 'hi!'
		console.log(data);
	});
	conn.on("open", () => {
		conn.send("hello!");
	});
});

Media calls

Call

navigator.mediaDevices.getUserMedia(
	{ video: true, audio: true },
	(stream) => {
		const call = peer.call("another-peers-id", stream);
		call.on("stream", (remoteStream) => {
			// Show stream in some <video> element.
		});
	},
	(err) => {
		console.error("Failed to get local stream", err);
	},
);

Answer

peer.on("call", (call) => {
	navigator.mediaDevices.getUserMedia(
		{ video: true, audio: true },
		(stream) => {
			call.answer(stream); // Answer the call with an A/V stream.
			call.on("stream", (remoteStream) => {
				// Show stream in some <video> element.
			});
		},
		(err) => {
			console.error("Failed to get local stream", err);
		},
	);
});

Running tests

npm test

Browser support

Firefox
Firefox
Chrome
Chrome
Safari
Edge
Safari
Safari
80+ 83+ 83+ 15+

We test PeerJS against these versions of Chrome, Edge, Firefox, and Safari with BrowserStack to ensure compatibility. It may work in other and older browsers, but we don't officially support them. Changes to browser support will be a breaking change going forward.

Note

Firefox 102+ is required for CBOR / MessagePack support.

FAQ

Q. I have a message Critical dependency: the request of a dependency is an expression in browser's console

A. The message occurs when you use PeerJS with Webpack. It is not critical! It relates to Parcel parcel-bundler/parcel#2883 We'll resolve it when updated to Parcel V2.

Links

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

PeerJS is licensed under the MIT License.

peerjs's People

Contributors

afrokick avatar akotynski avatar caballerog avatar capripio avatar che-burashco avatar code-factor avatar deepsource-autofix[bot] avatar dependabot[bot] avatar dmitry-kurmanov avatar ericz avatar fippo avatar hansoksendahl avatar harshcasper avatar hnry avatar jhamit avatar jonasgloning avatar khankuan avatar kidandcat avatar lmb avatar mhchia avatar michelle avatar michelle-stripe avatar monkeywithacupcake avatar nexts avatar prashoon123 avatar preya avatar psanders avatar renovate[bot] avatar semantic-release-bot avatar xizhao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

peerjs's Issues

Nicer documentation.

Perhaps use Jekyll to generate a nice documentation page with links and all that fancy stuff we don't currently have, since it's already in md.

Security enhancements

See discussion in #23

  • Tokens are generated with Math.random() and thus have poor entropy
  • Server deletes clients immediately upon disconnect, preventing possibility of reconnection under same id/token.
  • HTTPS support needs to be deployed due to possible snooping of id/token in request URIs

Provide a method Peer.close();

Hey,

first of all: Nice work!

I have a whish for an improvement: For 1:1 application it would be nice if the connection to the key server can be closed after a p2p connection has been established. So i think it would be useful if there is Peer.close() method.

Best regards
Matthias

Encrypted connection.

From WebRTC spec: 'To prevent network sniffing from allowing a fourth party to establish a connection to a peer using the information sent out-of-band to the other peer and thus spoofing the client, the configuration information should always be transmitted using an encrypted connection.'

Can't Send > 1024 Bytes of Data

Hey, I cant send more then 1024 bytes of data atall, from one tab to other even in the basic chat demo ..

Is there anything wrong ? or is it just my internet connection fault or something ?

reliable does not work due to type and something else

typo where reliable is not getting passed thru to connections!

Once it does get through, somehow the data events don't get emitted from the client.

Thanks for a cool project mb and ez!
Here is my repro: http://github.com/dtrejo/peerimage

/** Create and returns a DataConnection with the peer with the given label. */
ConnectionManager.prototype.connect = function(label) {
  if (!this.open) {
    return;
  }

+  var options = util.extend({
+    reliable: false,
+    serialization: 'binary',
+    label: label || 'peerjs'
+  }, this._options);

Tag naming typo?

Hey,

is there maybe a little typo by tag naming? There is a tag 1.8.0 where i think this should be 0..8. Then it would match the timeline, too... ;)

Best regards
Matthias

Incorrect Message Sizes

Version 28.0.1500.20 beta on Mac

I sent a message of length 1000 characters, and received a string of length 999.

This consistently occurs.

Large file transfer progress

What is the best way to get information about the progress of an ongoing large file transfer? Is there any?

Keep up the great work!
Kind regards,
Sebastian

Chinese characters don't work

i took your chat.html example, and attempted to make it work with UTF8

new Peer({key: '47etzdhjw597ldi', debug: true, serialization: 'binary-utf8'})

but it still has the following effect.

a string of characters get cut off

send: "普通话"
receive: "普"

and certain characters get combined

send: "你好"
receive: "佀"

is this a problem with the protocol, or the library?

Error events

Emit some sort of error event for incompatible browser & list the features needed/missing.

Also differentiation of errors in general (ID taken, etc) that would typically want to be handled; make it easy to tell which are fatal (thus destroying the Peer) and which are recoverable.

Adapter fixes.

  • PeerConnection [and Session Description, getUserMedia, browserisms, etc] should not depend on existence and browser attribution of getUserMedia.
  • Clean up code; for DataConnection, getUserMedia is not required.
  • Consider whether PeerConnection, et al should be exported or confined to PeerJS scope.

this._socket is undefined

in firefox/phantom js, in chrome anything is ok. (latest versions)

/**
* Disconnects the Peer's connection to the PeerServer. Does not close any
* active connections.
* Warning: The peer can no longer create or accept connections after being
* disconnected. It also cannot reconnect to the server.
*/
Peer.prototype.disconnect = function() {
if (!this.disconnected) {
>> this._socket.close();
this.id = null;
this.disconnected = true;
}
}; 

build with browserify?

May I suggest building this with browserify rather than using an ad-hoc build script?

The overhead added by browserify v2 is tiny, and it allows you access all the modules on npm!

Since the overhead is so small, it would still be possible to distribute via a minified script tag.

Unauthorized POST requests during signalling!

POST http://0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate 401 (Unauthorized) 0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate:1
POST http://0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate 401 (Unauthorized) 0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate:1
POST http://0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate 401 (Unauthorized) 0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate:1
POST http://0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate 401 (Unauthorized) 0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate:1
POST http://0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate 401 (Unauthorized) 0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate:1
POST http://0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate 401 (Unauthorized) 0.peerjs.com:9000/byuxn9ec1r4fgvi/sender/cn8n9tcwppop3nmi/candidate:1

session hijacking?

I looked over peer server, and it appears that there is the possibility of session hijacking?

It would not be hard to randomly guess an active ID of another peer.

Once they do, they could connect with that peer randomly. (Even if user developer has a confirmation for incoming connection, it's still weird to randomly receive a connect. But mainly this serves as confirmation that the ID is active).

Once you confirm the ID is active, you can override the existing Peer by using that ID (the peer server does nothing to stop this?). So any incoming connection meant for the existing Peer now go to you.

When you consider that existing Peers could be in the thousands, the success rate is much higher.

  • IDs & tokens are too short
  • IDs & tokens should not be generated client side
  • use tokens as a CSRF token and they should be signed

Also, server needs to ensure IDs are unique.

[UPDATE: to be more in the form of a question / possibility]

ArrayBuffer values are deprecated in Blob Constructor

In peer.js (build 0.1.0), I'm getting a warning (on row 1108) in Chrome Canary version 27.0.1443.0 saying: ArrayBuffer values are deprecated in Blob Constructor. Use ArrayBufferView instead.
It doesn't break anything, but it might be nice to fix.

Multiple channels

Allow to open several simultaneous channels with the same peer, so each one can use a different protocol.

peer.connect() TypeError: Not enough arguments to mozRTCPeerConnection.createOffer.

Firefox Nightly 24.0a1, Ubuntu 12.04.

I'm getting this error: TypeError: Not enough arguments to mozRTCPeerConnection.createOffer. @ http://cdn.peerjs.com/0/peer.js:1799

This occurs with peer.connect(). When listening to peer.on("open"), the client does connect to the server, but I'm having trouble connecting peers due to this error.

var peer = new Peer('some-id', {host: 'localhost', port: 9000});                

peer.on('connection', function(conn) {                                          
  conn.on('data', function(data){                                               
    // Will print 'hi!'                                                         
    console.log(data);                                                          
  });                                                                           
});                                                                             

var conn = peer.connect('some-id');                                             
conn.on('open', function() {                                                    
  conn.send('Hello world!');                                                    
});

Socket.prototype.start & Event Emitters

I don't know about Socket.prototype.start, it seems that it could be better implemented? Trying to start a websocket and xhr connection seem fine more for compatibility reasons than latency?
As I'm pretty sure xhr will always win in that case, since it has less overhead.

The other thing is I think the way event emitters are used could be better implemented, that is, that everything is tightly coupled, which doesn't seem good.

Do you Mr. Zhang & Ms. Bu agree? Thoughts?

track mobile browsers on status pages

especially Chrome (Stable/Beta) for Android and Firefox (Stable/Beta) for Android
had luck connecting chrome android <-> desktop, but not firefox-es, in any combinations

Collaborate with other p2p projects

I'm trying to work on arbitary p2p topology construction code. To do that a topology needs a list of possible peers in the network and a mechanism for connecting to peers.

If we can standardize on an API for these building blocks we can build re-usable code!

Firefox support

Most of the stuff I read seems to indicate firefox supports datachannel of the updated spec, with the notable exception of connectDataConnection. Are there major reasons for not trying to support firefox, as I see compatibility page shows that not even 22.0a1 will run peerjs which is rather far into the future?

Error trying code from Getting started guide

Trying the code in Getting started guide, I get this error in Google Chrome console:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

Opening the link in a new tab, this is the json sent with header 401:

{"code":"MethodNotAllowedError","message":"GET is not allowed"}

Am I missing a required step?

Calling connect before Peer opens does not work consistently.

Could be that socket is not always open when ConnectionManager is initialized and we don't have to wait for an id.

"I'm using latest chrome 27.0.1453.94 ...
I've checked it a bit more and it seems to be related to the time between creating a new Peer and using the object itself.
before today I was using the Peer.connect() method or the Peer.on() method right after calling the constructor."

Improve demo[s].

  • Simple example; clean, bare bones code.
  • Fancy chatroom with peer routing and flying pigs and icing.
  • Better file upload interface.

Bidirectional Streams?

When peer 1 connects with peer 2, both update their peer.connections object, but I was only able to get peer 1 to actually send peer 2 data. Peer 2 would not send data to peer 1.
After manually connecting peer 2 to peer 1, the situation reverses: peer 1 cannot send messages to peer 2, but peer 2 can send messages to peer 1.

These streams are supposed to be bidirectional, right?

Do you support reliable data channels?

How do you handle the fact that datachannel implementations in chome are currently unreliable.

How is the chrome <-> firefox data channel interop.

Do you have a fallback for datachannel's in non webrtc browsers?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.