Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'simple-peer' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
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)
}
/* 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');
}
// 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}
*/
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
}
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 () {
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,
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?
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
}
constructor(){
super();
if(Peer.WEBRTC_SUPPORT){ // test for webrtc support
this.state = {
role: 'visitor'
};
} else {
this.state = {
role: 'unsupported',
playingGame: false
};
}
}
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) {