Not enough arguments to RTCPeerConnection.setRemoteDescription [duplicate] - javascript

This question already has an answer here:
RTCPeerConnection.createAnswer callback returns undefined object in mozilla for WebRTC chat
(1 answer)
Closed 4 years ago.
Currently having the follow error in Firefox 64 where its giving this error which I have been searching online for a working fix but could not find one.
TypeError: "Not enough arguments to RTCPeerConnection.setRemoteDescription."
Been using a few of the links to fix but to no avail and also the latter is outdated.
https://developer.mozilla.org/en-US/docs/Web/API/RTCSessionDescription
WebRTC Firefox: Not enough arguments to RTCPeerConnection.setLocalDescription
Chrome triggers another error which is main.js:58 Uncaught TypeError: Cannot read property 'type' of undefined and this is when there's a if statement to check if the remotedescription.type matches offer
Would be grateful if anyone knows a fix.
'use strict';
var configuration = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
};
var pc = new RTCPeerConnection(configuration);
// Define action buttons.
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
/////////////////////////////////////////////
window.room = prompt('Enter room name:');
var socket = io.connect();
if (room !== '') {
console.log('Message from client: Asking to join room ' + room);
socket.emit('create or join', room);
}
socket.on('created', function(room) {
console.log('Created room ' + room);
startVideo();
});
socket.on('full', function(room) {
console.log('Message from client: Room ' + room + ' is full :^(');
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
startVideo();
callButton.disabled = true;
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
async function sendMessage(message) {
console.log('Client sending message: ', message);
await socket.emit('message', message);
}
// This client receives a message
socket.on('message', async message => {
if (message.sdp) {
await pc
.setRemoteDescription(new RTCSessionDescription(message.sdp), () => {
if (pc.remotedescription.type === 'offer') {
pc.setLocalDescription(pc.createAnswer())
.then(function() {
sendMessage({ sdp: pc.localDescription });
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
} else {
pc.addIceCandidate(new RTCIceCandidate(message.candidate)).catch(
error => console.error(error)
);
}
})
.catch(error => console.error(error));
}
});
pc.onicecandidate = event => {
if (event.candidate) {
sendMessage({ candidate: event.candidate });
}
};
pc.ontrack = event => {
if (remoteVideo.srcObject !== event.streams[0]) {
remoteVideo.srcObject = event.streams[0];
console.log('Got remote stream');
}
};
////////////////////////////////////////////////////
const localVideo = document.querySelector('#localVideo');
const remoteVideo = document.querySelector('#remoteVideo');
// Set up initial action buttons status: disable call and hangup.
callButton.disabled = true;
hangupButton.disabled = true;
// Add click event handlers for buttons.
callButton.addEventListener('click', callStart);
hangupButton.addEventListener('click', hangupCall);
function startVideo() {
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true
})
.then(function(stream) {
localVideo.srcObject = stream;
stream.getTracks().forEach(track => pc.addTrack(track, stream));
})
.catch(function(err) {
console.log('getUserMedia() error: ' + err.name);
});
callButton.disabled = false;
}
async function callStart() {
callButton.disabled = true;
hangupButton.disabled = false;
console.log('Sending offer to peer');
await pc
.setLocalDescription(await pc.createOffer())
.then(function() {
sendMessage(pc.localDescription);
})
.catch(err => {
console.log(err.name + ': ' + err.message);
});
}
/////////////////////////////////////////////////////////
function hangupCall() {
pc.close();
pc = null;
callButton.disabled = false;
hangupButton.disabled = true;
console.log('Call Ended');
}

You are calling pc.setRemoteDescription(desc, callback) but do not provide an error callback, using a .catch instead. Firefox does not like using a callback without providing an error callback as well which leads to the "Not enough arguments" error.
Don't mix the deprecated callbacks with promises but instead use pc.setRemoteDescription(desc).then(() => ...).catch(...)

Related

Error "Function returned undefined, expected Promise or value" even after return in all places

I am new to Node.js and I am struggling with Promises even after reading the tutorials provided by other stackflow users. I have already spent a whole evening on this and I am looking for help. I get the following error " Function returned undefined, expected Promise or value". My code is below. What am I doing wrong? I also have a suspicion that I have to use await/async because it looks like my code is running through without waiting for the first get to complete.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
var db = admin.firestore();
exports.declinedRequest = functions.firestore
.document('requests/{requestId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
const status = newValue.status;
const request = context.params.requestId;
var registrationToken;
var message;
if(status=="created") {
console.log('Checkpoint1 ',context.params.requestId);
newValue.friends.forEach(doc => {
console.log('Checkpoint 2: ', doc);
var usersRef = db.collection('users');
var query = usersRef.where('mobile', '==', doc).get()
.then(snapshotFriend => {
if (snapshotFriend.empty) {
console.log('Checkpoint3.');
return;
}
snapshotFriend.forEach(mobile => {
registrationToken = mobile.data().fcmToken;
console.log('FCM token =>', registrationToken);
if (!registrationToken) {
console.log('No fcmToken available');
return;
}
message = {
notification: {
body: "Request still available from " + newValue.requesterName,
sound: "default",
badge: 1
},
data: {
requestId: `${request}`
}
};
console.log('FCM token message created');
})
})
})
} else {
return;
}
return admin.messaging().sendToDevice(registrationToken, message)
.then(function (response) {
console.log("Successfully sent message:", response)
})
.catch(function (error) {
console.log("Error sending message:", error);
})
})
Try the code below hope this will work.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const Promise = require('bluebird');
const _ = require('lodash');
let db = admin.firestore();
exports.declinedRequest = functions.firestore
.document('requests/{requestId}')
.onUpdate((change, context) => {
const newValue = change.after.data();
const status = newValue.status;
const request = context.params.requestId;
if (status == "created") {
console.log('Checkpoint1 ', context.params.requestId);
allPromises = [];
newValue.friends.forEach(doc => {
console.log('Checkpoint 2: ', doc);
const usersRef = db.collection('users');
// query for each document return promise.
allPromises.push(queryForEachDocument(doc,request,usersRef));
});
return Promise.all(allPromises);
} else {
return Promise.reject / resolve('Whatever you want.');
}
})
function queryForEachDocument(doc,request,usersRef) {
let promiseInvoices = []
let registrationToken;
let message;
return usersRef.where('mobile', '==', doc).get().then((snapshotFriend) => {
if (_.isEmpty(snapshotFriend)) {
console.log('Checkpoint3.');
return Promise.reject(new Error('Your error'));
}
snapshotFriend.forEach(mobile => {
registrationToken = mobile.data().fcmToken;
console.log('FCM token =>', registrationToken);
if (!registrationToken) {
console.log('No fcmToken available for', newValue.requesterName);
// Do anything you want to change here.
return Promise.reject(new Error('No fcmToken available for',newValue.requesterName));
}
message = {
notification: {
body: "Request still available from " + newValue.requesterName,
sound: "default",
badge: 1
},
data: {
requestId: request
}
};
console.log('FCM token message created');
// send invoice for each registrationToken
promiseInvoices.push(sendInvoice(registrationToken, message))
});
}).then(() => {
return Promise.all(promiseInvoices);
})
}
function sendInvoice(registrationToken, message) {
return admin.messaging().sendToDevice(registrationToken, message)
.then(function (response) {
console.log("Successfully sent message:", response)
})
.catch(function (error) {
console.log("Error sending message:", error);
})
}

Remote video on both sides won't show up

Currently using Chrome 70, Firefox 64 and Safari 12.
The remote video from the other user is not getting displayed on both sides and I am not quite sure what could be the issue.
There is no errors coming from any of the browsers which does not help in debugging the code.
I am using chrome's internal WebRTC debugging tool (chrome://webrtc-internals) and there is zero packets that have been sent or received.
There's a parameter in the tool which is googCandidatePair but this does not show up at all during a call.
ICEgatheringstatechange event triggers and state that it has completed but only when the host is the chrome user.
I have also tried using
pc.oniceconnectionstatechange = () => console.log(pc.iceConnectionState);
to check for the ICE state changes but this does not trigger at all.
One reason I think it might not be working correctly could be due to how RTCPeerconnection was configured as from this picture, the Ice candidate pool size is 0 but it was never stated in the code itself.
Below are 2 pictures where the first one is when the host is chrome and the other being the receiver
The code is as follows :
'use strict';
var configuration = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
};
var pc = new RTCPeerConnection(configuration);
// Define action buttons.
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
/////////////////////////////////////////////
window.room = prompt('Enter room name:');
var socket = io.connect();
if (room !== '') {
console.log('Message from client: Asking to join room ' + room);
socket.emit('create or join', room);
}
socket.on('created', function(room) {
console.log('Created room ' + room);
startVideo();
});
socket.on('full', function(room) {
console.log('Message from client: Room ' + room + ' is full :^(');
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
startVideo();
callButton.disabled = true;
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
async function sendMessage(message) {
console.log('Client sending message: ', message);
await socket.emit('message', message);
}
// This client receives a message
socket.on('message', message => {
if (message.sdp) {
pc.setRemoteDescription(new RTCSessionDescription(message.sdp))
.then(function() {
if (pc.setRemoteDescription.type === 'offer') {
pc.setLocalDescription(pc.createAnswer())
.then(function() {
sendMessage({ sdp: pc.localDescription });
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
}
})
.catch(error => console.error(error));
} else if (message.candidate) {
pc.addIceCandidate(new RTCIceCandidate(message.candidate))
.then(() => {
console.log('Candidates received');
})
.catch(error => console.error(error));
}
});
pc.onicecandidate = event => {
if (event.candidate) {
sendMessage({ candidate: event.candidate });
}
};
pc.ontrack = event => {
if (remoteVideo.srcObject !== event.streams[0]) {
remoteVideo.srcObject = event.streams[0];
console.log('Got remote stream');
}
};
////////////////////////////////////////////////////
const localVideo = document.querySelector('#localVideo');
const remoteVideo = document.querySelector('#remoteVideo');
// Set up initial action buttons status: disable call and hangup.
callButton.disabled = true;
hangupButton.disabled = true;
// Add click event handlers for buttons.
callButton.addEventListener('click', callStart);
hangupButton.addEventListener('click', hangupCall);
function startVideo() {
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true
})
.then(function(stream) {
localVideo.srcObject = stream;
stream.getTracks().forEach(track => pc.addTrack(track, stream));
})
.catch(function(err) {
console.log('getUserMedia() error: ' + err.name);
});
callButton.disabled = false;
}
async function callStart() {
callButton.disabled = true;
hangupButton.disabled = false;
console.log('Sending offer to peer');
await pc
.setLocalDescription(await pc.createOffer())
.then(() => {
sendMessage({ sdp: pc.localDescription });
})
.catch(err => {
console.log(err.name + ': ' + err.message);
});
}
/////////////////////////////////////////////////////////
function hangupCall() {
pc.close();
pc = null;
callButton.disabled = false;
hangupButton.disabled = true;
console.log('Call Ended');
}
You're mixing your promise styles, and you have a bug here:
pc.setLocalDescription(pc.createAnswer()) // bug!
.then(function() {
The above sets the local description to a promise object. Either pick async/await throughout:
await pc.setLocalDescription(await pc.createAnswer());
...or .then() chains:
pc.createAnswer()
.then(answer => pc.setLocalDescription(answer))
.then(function() {
If you pick the latter, don't forget to return all the promises.
Here's the message handler done solely with async/await:
// This client receives a message
socket.on('message', async message => {
try {
if (message.sdp) {
await pc.setRemoteDescription(message.sdp);
if (pc.setRemoteDescription.type === 'offer') {
await pc.setLocalDescription(await pc.createAnswer());
sendMessage({sdp: pc.localDescription});
}
} else if (message.candidate) {
await pc.addIceCandidate(message.candidate);
console.log('Candidates received');
}
} catch (err) {
console.log(err.name + ': ' + err.message);
}
}
If anyone might have problems with the remote video not showing up, I found out that it was because the message was not through the second IF statement that was checking if message.type === offer and since it could not create the answer thus it could not send its local description over to the other user. But by splitting the message up at the start to sdp and candidate, it somehow works.
socket.on('message', async ({ sdp, candidate }) => {
if (sdp) {
await pc.setRemoteDescription(new RTCSessionDescription(sdp));
if (sdp.type === 'offer') {
await pc
.setLocalDescription(await pc.createAnswer())
.then(function() {
sendMessage({ sdp: pc.localDescription });
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
}
} else if (candidate) {
await pc
.addIceCandidate(new RTCIceCandidate(candidate))
.then(() => {
console.log('Candidates received');
})
.catch(error => console.error(error));
}
});

Failed to execute 'setLocalDescription' on 'RTCPeerConnection

I have been having this error for a while
Have been trying to use async to wait for the local description to be updated but as how my code works right now it would not be able to integrate it and also I heard that socket.on already does async itself.
I have also tried using breakpoints in vs code to debug the code which doesn't work well.
Would greatly appreciate if anyone knows a workaround for this.
The code is attached below
'use strict';
var localStream;
var remoteStream;
var isInitiator;
var configuration = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
};
var pc = new RTCPeerConnection(configuration);
// Define action buttons.
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
/////////////////////////////////////////////
window.room = prompt('Enter room name:');
var socket = io.connect();
if (room !== '') {
console.log('Message from client: Asking to join room ' + room);
socket.emit('create or join', room);
}
socket.on('created', function(room) {
console.log('Created room ' + room);
isInitiator = true;
startVideo();
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
startVideo();
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
function sendMessage(message) {
socket.emit('message', message);
}
// This client receives a message
socket.on('message', function(message) {
try {
if (message.type === 'offer') {
pc.setRemoteDescription(new RTCSessionDescription(message));
// const stream = navigator.mediaDevices.getUserMedia({
// audio: true,
// video: true
// });
// stream.getTracks().forEach(track => pc.addTrack(track, localStream));
pc.setLocalDescription(
pc.createAnswer(setLocalAndSendMessage, function(err) {
console
.log(err.name + ': ' + err.message)
.then(pc.setLocalDescription);
})
);
} else if (message.type === 'answer') {
console.log('This is to check if answer was returned');
pc.setRemoteDescription(new RTCSessionDescription(message));
} else if (message.type === 'candidate') {
pc.addIceCandidate(candidate);
}
} catch (err) {
console.error(err);
}
});
////////////////////////////////////////////////////
const localVideo = document.querySelector('#localVideo');
const remoteVideo = document.querySelector('#remoteVideo');
// Set up initial action buttons status: disable call and hangup.
callButton.disabled = true;
hangupButton.disabled = true;
// Add click event handlers for buttons.
callButton.addEventListener('click', callStart);
hangupButton.addEventListener('click', hangupCall);
function startVideo() {
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true
})
.then(function(mediaStream) {
localStream = mediaStream;
localVideo.srcObject = mediaStream;
})
.catch(function(err) {
console.log('getUserMedia() error: ' + err.name);
});
callButton.disabled = false;
}
function callStart() {
createPeerConnection();
//pc.addTrack(mediaStream);
//stream.getTracks().forEach(track => pc.addTrack(track, localStream));
callButton.disabled = true;
hangupButton.disabled = false;
if (isInitiator) {
console.log('Sending offer to peer');
pc.createOffer(setLocalAndSendMessage, function(err) {
console.log(err.name + ': ' + err.message).then(pc.setLocalDescription);
});
}
}
/////////////////////////////////////////////////////////
function createPeerConnection() {
try {
pc = new RTCPeerConnection(null);
pc.onicecandidate = ({ candidate }) => sendMessage({ candidate });
pc.ontrack = event => {
if (remoteVideo.srcObject) return;
remoteVideo.srcObject = event.streams[0];
};
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
return;
}
}
function setLocalAndSendMessage(sessionDescription) {
console.log('setLocalAndSendMessage sending message', sessionDescription);
pc.setLocalDescription(sessionDescription);
sendMessage(sessionDescription);
}
function hangupCall() {
pc.close();
pc = null;
}
There is no workaround to understanding asynchronous code. You're cut'n'pasting your way here.
If you're not going to use async/await, then you need to contend with that JavaScript is single-threaded, and can't ever block to wait for an asynchronous operation to finish, so you can never just use the return value from an asynchronous method directly, like you're trying to do here:
createAnswer is an asynchronous method, returning a promise, not an answer, so this is wrong:
pc.setLocalDescription( // <-- wrong
pc.createAnswer(setLocalAndSendMessage, function(err) { //
console
.log(err.name + ': ' + err.message)
.then(pc.setLocalDescription);
})
);
You're calling setLocalDescription(promise), which gives you the error you mention, since a promise is not a valid description. Instead, a promise is an object you attach callbacks to:
const promise = pc.createAnswer();
promise.then(setLocalAndSendMessage, function(err) {
console.log(err.name + ': ' + err.message);
});
or simply:
pc.createAnswer()
.then(setLocalAndSendMessage, function(err) {
console.log(err.name + ': ' + err.message);
});
We can even use then successively to form a promise chain:
pc.createAnswer()
.then(function(answer) {
return pc.setLocalDescription(answer);
})
.then(function() {
sendMessage(pc.localDescription);
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
Also, I shouldn't have to tell you console.log() does not return a promise!
Sadly, you're copying really old code here, and RTCPeerConnection has some legacy APIs and does some tricks to sometimes let callers get away with calling these negotiation methods without truly promise-chaining or checking for errors. But it inevitably leads to trouble.

Error promise after publish data to MQTT broker in My Alexa Lambda node js

I have problem with my Lambda, actually in promise nodejs. I have wrote code like this in my Lambda:
'use strict'
const Alexa = require('alexa-sdk');
const mqtt = require('mqtt');
const APP_ID = undefined;
const WELCOME_MESSAGE = 'Welcome to the lamp control mode';
const WELCOME_REPROMT = 'If you new please say help'
const HELP_MESSAGE = 'In this skill you can controlling lamp to turn off or on, dim the lamp, change the lamp color and schedule the lamp';
const STOP_MESSAGE = 'Thanks for using this skill, Goodbye!';
const OFF_RESPONSE = 'Turning off the lamp';
const ON_RESPONSE = 'Turning on the lamp';
const DIM_RESPONSE = 'Dimming the lamp';
const CHANGE_RESPONSE = 'Changing the lamp color';
const AFTER_RESPONSE = 'Wanna control something again ?';
const handlers = {
'LaunchRequest': function () {
this.emit(':ask', WELCOME_MESSAGE, WELCOME_REPROMT);
},
'OnOffIntent' : function () {
var status = this.event.request.intent.slots.status.value;
var location = this.event.request.intent.slots.location.value;
console.log(status);
console.log(location);
if (status == 'on') {
// Promise Start
var mqttPromise = new Promise(function(resolve, reject) {
var options = {
port: '1883',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'username',
password: 'password',
};
var client = mqtt.connect('mqtt://broker-address', options)
client.on('connect', function() {
client.publish("lamp/status", status + ' ' + location, function() {
console.log("Message is published");
client.end();
resolve('Done Sending');
});
});
});
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
);
// Promise END
// this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
// client.publish("lamp/status", status + ' ' + location);
} else if (status == 'off') {
this.emit(':ask', OFF_RESPONSE, AFTER_RESPONSE);
// client.publish("lamp/status", status + ' ' + location);
}
},
'DimIntent' : function () {
// to do here
},
'ChangeColorIntent' : function () {
// to do here
},
'ShceduleIntent' : function () {
// to do here
},
'AMAZON.HelpIntent': function () {
this.emit(':ask', HELP_MESSAGE, 'Wanna control something ?');
},
'AMAZON.StopIntent': function () {
this.emit(':tell', STOP_MESSAGE);
}
};
exports.handler = function (event, context, callback) {
const alexa = Alexa.handler(event, context, callback);
alexa.APP_ID = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
}
I test my code with Service Simulator in Alexa Developer and get this result :
Result Image
So I checked output in Lambda and I got this error report :
Error in Lamda
Can anyone please help me? I have no idea with this because this is my first trial :)
The crux of your error seems to be this specific line in the log:
Cannot read property 'emit' of undefined
And after following the flow of your program, it's likely ocurring here:
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
// It's probably ocurring in this line below
this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
)
The log is saying that you tried using this, it's undefined and doesn't have an emit property. Thats ocurring because of how this works in Js. You could workaround this problem by saving a reference to this
var that = this;
var mqttPromise = new Promise(function(resolve, reject) {
var options = {
port: '1883',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'username',
password: 'password',
};
var client = mqtt.connect('mqtt://broker-address', options)
client.on('connect', function() {
client.publish("lamp/status", status + ' ' + location, function() {
console.log("Message is published");
client.end();
resolve('Done Sending');
});
});
});
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
that.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
);
I would also recommend reading up a bit on "How 'this' works in Javascript"
MDN
Stack Overflow - "how does 'this' work"

WebRTC video chat

I am trying to build a 1-to-1 video chat with webrtc and the RTCPeerConnection API. A problem with my code is that after an initial user connects to the server, it doesn't receive messages from the server when other users emit messages via socket.io. The clients only receive their own emitted messages. Here is some of my code. The full project is on Github at: https://github.com/rashadrussell/webrtc_experiment
Client-Side
var isInitiator = false;
socket.on('initiatorFound', function(data) {
isInitiator = data.setInitiator;
console.log("Is Initiator? " + isInitiator);
});
navigator.getMedia = (
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia
);
navigator.getMedia(
{video: true, audio: false},
function(stream) {
var video = document.getElementById("localView");
video.src = window.URL.createObjectURL(stream);
console.log("Add Stream");
sendMessage('streamAdd', {streamAdded: 'stream-added'});
createPeerConnection();
pc.addStream(stream);
if(isInitiator)
{
callPeer();
}
},
function(err) {
console.log("The following error occured: ");
console.dir(err);
}
);
function sendMessage(type, message)
{
console.log("Sending Message");
socket.emit('message',{
"type": type,
"message": message
});
}
function createPeerConnection() {
pc = new rtcPeerConnection(servers, options);
console.dir(pc);
pc.onicecandidate = function(evt) {
if(evt.candidate == null) return;
pc.onicecandidate = null;
console.log("Send Ice Candidate");
sendMessage("iceCandidate", JSON.stringify(evt.candidate));
};
pc.onaddstream = function(evt) {
document.body.append("<video id='remoteVideo' autoplay></video>");
var remoteVid = document.getElementById("remoteVideo");
remoteVid.src = window.URL.createObjectURL(evt.stream);
};
}
function callPeer() {
pc.createOffer(function (offer) {
pc.setLocalDescription(offer, function() {
sendMessage("offer", JSON.stringify(offer));
});
console.log("Send Offer");
}, function(err) { console.log("Offer Error: " + err) },
videoConstraints
);
}
function answerPeer() {
pc.createAnswer(function(answer) {
pc.setLocalDescription(answer);
sendMessage("answer", JSON.stringify(answer))
}, function(err) { console.log("Sending Answer Error: " + err) },
videoConstraints
);
}
socket.on('message', function(message) {
console.log("CONSOLE MESSAGE:");
console.dir(message);
if(message.type == 'streamAdd') {
console.log('Stream was added');
createPeerConnection();
if(isInitiator) {
callPeer();
}
} else if(message.type == 'offer') {
pc.setRemoteDescription( new rtcSessionDescription(JSON.parse(message.message)));
if(!isInitiator)
{
console.log("Sending Answer");
answerPeer();
}
} else if(message.type == 'answer') {
pc.setRemoteDescription( new rtcSessionDescription(JSON.parse(message.message)));
} else if(message.type == 'iceCandidate') {
console.log("Get Ice Candidate");
pc.addIceCandidate(new rtcIceCandidate(JSON.parse(message.message)) );
}
});
Server-Side
var isInitiator = false;
io.sockets.on('connection', function(socket) {
if (!isInitiator) {
isInitiator = true;
socket.emit('initiatorFound', {setInitiator: isInitiator});
} else {
socket.emit('initiatorFound', {setInitiator: !isInitiator});
}
// Signaling Channel
socket.on('message', function(message) {
if (message.type == 'streamAdd') {
console.log('Got message: ' + message);
}
//socket.emit('message' ,message);
// Should be:
socket.broadcast.emit('message', message);
});
});
See if you want to send message to particular user you set unique ID(socket.id) but now you are try just testing correct so change your server side code
var isInitiator = false;
io.sockets.on('connection', function(socket) {
if (!isInitiator) {
isInitiator = true;
socket.emit('initiatorFound', {setInitiator: isInitiator});
} else {
socket.emit('initiatorFound', {setInitiator: !isInitiator});
}
// Signaling Channel
socket.on('message', function(message) {
if (message.type == 'streamAdd') {
console.log('Got message: ' + message);
}
socket.emit('message' ,message);
});
});
see here socket.emit('message',message); this socket object contain your id so its send a message to you if you want do send a message to particular user you know the unique.id any way send message to every connection expect this socket(mean current socket)
io.sockets.on('connection', function(socket) {
if (!isInitiator) {
isInitiator = true;
socket.emit('initiatorFound', {setInitiator: isInitiator});
} else {
socket.emit('initiatorFound', {setInitiator: !isInitiator});
}
// Signaling Channel
socket.on('message', function(message) {
if (message.type == 'streamAdd') {
console.log('Got message: ' + message);
}
socket.broadcast.emit('message' ,message);
});
});
I figured out why the other clients weren't being notified when a message is emitted. In my server-side code, under the signaling channel section, socket.emit is supposed to be socket.broadcast.emit or io.sockets.emit.
Socket.emit only relays the message back to the client who initiated the call the server. socket.broadcast.emit relays the message to all clients except for the client who initiated the call, and io.sockets.emit relays the message to all clients including the client who initiated the call.

Categories

Resources