How to use simple-peer - 10 common examples

To help you get started, we’ve selected a few simple-peer examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github maidsafe / safe_examples / webrtc_app / src / components / PeerView.js View on Github external
setUpPeer (props) {
    // we've already started setup
    if (this.peer) return
    this.setState({
      'connectionState': 'connecting'
    })

    console.log('trying', props)
    // we need both to start up
    if (!props.stream || !props.authorised) return

    // FIXME: this should move into the store

    const initiator = !props.peerPayload
    const peer = new Peer({ initiator: initiator,
                          stream: props.stream,
                          config : {
                            iceServers: CONFIG.iceServers
                          },
                          trickle: false })
    const targetId = initiator ? props.room : props.peerPayload.targetId
    const myNewId = this.props.room + '-' + (Math.random())

    this.peer = peer
    console.log('mounting', initiator, targetId, props)

    if (!initiator) {
      // let's connect to the other peer
      peer.signal(props.peerPayload.payload)
    }
github kalm / kalm.js / packages / webrtc / src / webrtc.ts View on Github external
/* Requires ------------------------------------------------------------------*/

import Peer from 'simple-peer';

if (!Peer.WEBRTC_SUPPORT) {
  throw new Error('Unsupported environement for WebRTC');
}

/* Methods -------------------------------------------------------------------*/

function webrtc(config: WebRTCConfig = {}): KalmTransport {
  return function socket(params: ClientConfig, emitter: EventEmitter): Socket {
    let listener;

    function bind(): void {
      listener = new Peer();
      listener.on('connect', soc => emitter.emit('socket', soc));
      listener.on('error', err => emitter.emit('error', err));
      emitter.emit('ready');
    }
github webtorrent / webtorrent / index.js View on Github external
// Sometimes server.address() returns `null` in Docker.
      const address = this._tcpPool.server.address()
      if (address) this.torrentPort = address.port
    }

    this.emit('listening')
  }

  _debug () {
    const args = [].slice.call(arguments)
    args[0] = `[${this._debugId}] ${args[0]}`
    debug(...args)
  }
}

WebTorrent.WEBRTC_SUPPORT = Peer.WEBRTC_SUPPORT
WebTorrent.VERSION = VERSION

/**
 * Check if `obj` is a node Readable stream
 * @param  {*} obj
 * @return {boolean}
 */
function isReadable (obj) {
  return typeof obj === 'object' && obj != null && typeof obj.pipe === 'function'
}

/**
 * Check if `obj` is a W3C `FileList` object
 * @param  {*} obj
 * @return {boolean}
 */
github webtorrent / bittorrent-tracker / client.js View on Github external
let announce = typeof opts.announce === 'string'
      ? [opts.announce]
      : opts.announce == null ? [] : opts.announce

    // Remove trailing slash from trackers to catch duplicates
    announce = announce.map(announceUrl => {
      announceUrl = announceUrl.toString()
      if (announceUrl[announceUrl.length - 1] === '/') {
        announceUrl = announceUrl.substring(0, announceUrl.length - 1)
      }
      return announceUrl
    })
    announce = uniq(announce)

    const webrtcSupport = this._wrtc !== false && (!!this._wrtc || Peer.WEBRTC_SUPPORT)

    const nextTickWarn = err => {
      process.nextTick(() => {
        this.emit('warning', err)
      })
    }

    this._trackers = announce
      .map(announceUrl => {
        let parsedUrl
        try {
          parsedUrl = new URL(announceUrl)
        } catch (err) {
          nextTickWarn(new Error(`Invalid tracker URL: ${announceUrl}`))
          return null
        }
github enmasseio / linkup / src / peer / peer.js View on Github external
return new Promise((resolve, reject) => {
      var peer = new SimplePeer({ initiator: false });
      this.connections[message.from] = (peer);

      peer.on('error', function (err) {
        // TODO: reject promise?
        console.error(err);
      });

      peer.on('signal', function (data) {
        console.log('signal', data);

        if (data.type === 'answer') {
          resolve(data);
        }
      });

      peer.on('connect', function () {
github peer-calls / peer-calls / src / client / actions / PeerActions.ts View on Github external
const peerId = peer.id
    debug(
      'create peer: %s, hasStream: %s, initiator: %s',
      peerId, !!stream, initiator)
    dispatch(NotifyActions.warning('Connecting to peer...'))

    const oldPeer = getState().peers[peerId]
    if (oldPeer) {
      dispatch(NotifyActions.info('Cleaning up old connection...'))
      oldPeer.destroy()
      dispatch(removePeer(peerId))
    }

    debug('Using ice servers: %o', iceServers)

    const pc = new Peer({
      initiator,
      config: {
        iceServers,
        encodedInsertableStreams: true,
        // legacy flags for insertable streams
        enableInsertableStreams: true,
        forceEncodedVideoInsertableStreams: true,
        forceEncodedAudioInsertableStreams: true,
      },
      channelName: constants.PEER_DATA_CHANNEL_NAME,
      // trickle: false,
      // Allow the peer to receive video, even if it's not sending stream:
      // https://github.com/feross/simple-peer/issues/95
      offerConstraints: {
        offerToReceiveAudio: true,
        offerToReceiveVideo: true,
github samuelmaddock / metastream / old / WebRTCLobby.tsx View on Github external
private createPeer(userId: string): P2PConnection {
    const peer = new SimplePeer({
      initiator: !!this.props.host,
      trickle: false,
      config: {
        iceServers
      }
    });

    const conn = new P2PConnection(userId, peer);
    this.peers[userId] = conn;

    conn.on('data', (data: Buffer) => {
      this.receive(conn, data);
    });

    conn.on('close', () => {
      // TODO: emit event?
github samuelmaddock / metastream / packages / metastream-signal-server / src / client.ts View on Github external
private createPeer(options?: SimplePeer.Options): SimplePeer.Instance {
    const peer: any = new SimplePeer({ ...this.simplePeerOpts, ...options })

    // Ignore invalid ICE candidate errors
    // Chrome v75 and Firefox v68 have an incompatibility with trickle ICE
    // https://github.com/feross/simple-peer/issues/503
    peer.destroy = (err: any) => {
      if (typeof err === 'object' && err.code === 'ERR_ADD_ICE_CANDIDATE') return
      peer._destroy(err, () => {})
    }

    return peer
  }
github rynobax / jump-game / src / App.js View on Github external
constructor(){
    super();
    if(Peer.WEBRTC_SUPPORT){ // test for webrtc support
      this.state = {
        role: 'visitor'
      };
    } else {
      this.state = {
        role: 'unsupported',
        playingGame: false
      };
    }
  }
github yjs / y-webrtc / src / y-webrtc.js View on Github external
constructor (signalingConn, initiator, remotePeerId, room) {
    log('establishing connection to ', logging.BOLD, remotePeerId)
    this.room = room
    this.remotePeerId = remotePeerId
    this.closed = false
    this.connected = false
    this.synced = false
    /**
     * @type {any}
     */
    this.peer = new Peer({ initiator })
    this.peer.on('signal', signal => {
      publishSignalingMessage(signalingConn, room, { to: remotePeerId, from: room.peerId, type: 'signal', signal })
    })
    this.peer.on('connect', () => {
      log('connected to ', logging.BOLD, remotePeerId)
      this.connected = true
      // send sync step 1
      const provider = room.provider
      const doc = provider.doc
      const awareness = room.awareness
      const encoder = encoding.createEncoder()
      encoding.writeVarUint(encoder, messageSync)
      syncProtocol.writeSyncStep1(encoder, doc)
      sendWebrtcConn(this, encoder)
      const awarenessStates = awareness.getStates()
      if (awarenessStates.size > 0) {

simple-peer

Simple one-to-one WebRTC video/voice and data channels

MIT
Latest version published 3 years ago

Package Health Score

62 / 100
Full package analysis