Solve Socket.io connection in a external module with expressjs - node.js

I have the following case: When I try to connect the module called 'Signaling-Server.js'
in the view of html the console says: GET ERROR [HTTP/1.1 400 Bad Request 1ms]
But this only happens when I add these Module. When I try to connect without him the socket.io connections works perfectly.
app.js
//Modules
var express = require("express"),
http = require("http"),
morgan= require("morgan"),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
app = express(),
server = http.createServer(app),
io = require("socket.io").listen(server);
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended:false}));
app.use(bodyParser.json());
app.use(methodOverride());
app.set("views",__dirname + "/views");
//I need to 'onnect with this module
//require('./Signaling-Server.js')(myServerOrPort);
require('./Signaling-Server.js')(server);
//Server is ready
server.listen(3000);
The code of Signaling-Server is here (Cortesy of MuazKhan Proyect "RTCMultiConnection")
Signaling-Server.js
// Muaz Khan - www.MuazKhan.com
// MIT License - www.WebRTC-Experiment.com/licence
// Documentation - github.com/muaz-khan/RTCMultiConnection
module.exports = exports = function(app, socketCallback) {
var io = require('socket.io').listen(app, {
log: false,
origins: '*:*'
});
io.set('transports', [
'websocket', // 'disconnect' EVENT will work only with 'websocket'
'xhr-polling',
'jsonp-polling'
]);
var listOfUsers = {};
var shiftedModerationControls = {};
var ScalableBroadcast;
io.sockets.on('connection', function(socket) {
var params = socket.handshake.query;
var socketMessageEvent = params.msgEvent || 'RTCMultiConnection-Message';
if (params.enableScalableBroadcast) {
if (!ScalableBroadcast) {
ScalableBroadcast = require('./Scalable-Broadcast.js');
}
var singleBroadcastAttendees = params.singleBroadcastAttendees;
ScalableBroadcast(socket, singleBroadcastAttendees);
}
socket.userid = params.userid;
listOfUsers[socket.userid] = {
socket: socket,
connectedWith: {},
isPublic: false, // means: isPublicModerator
extra: {}
};
socket.on('extra-data-updated', function(extra) {
try {
if (!listOfUsers[socket.userid]) return;
listOfUsers[socket.userid].extra = extra;
for (var user in listOfUsers[socket.userid].connectedWith) {
listOfUsers[user].socket.emit('extra-data-updated', socket.userid, extra);
}
} catch (e) {}
});
socket.on('become-a-public-moderator', function() {
try {
if (!listOfUsers[socket.userid]) return;
listOfUsers[socket.userid].isPublic = true;
} catch (e) {}
});
socket.on('get-public-moderators', function(userIdStartsWith, callback) {
try {
userIdStartsWith = userIdStartsWith || '';
var allPublicModerators = [];
for (var moderatorId in listOfUsers) {
if (listOfUsers[moderatorId].isPublic && moderatorId.indexOf(userIdStartsWith) === 0 && moderatorId !== socket.userid) {
var moderator = listOfUsers[moderatorId];
allPublicModerators.push({
userid: moderatorId,
extra: moderator.extra
});
}
}
callback(allPublicModerators);
} catch (e) {}
});
socket.on('changed-uuid', function(newUserId) {
try {
if (listOfUsers[socket.userid] && listOfUsers[socket.userid].socket.id == socket.userid) {
if (newUserId === socket.userid) return;
var oldUserId = socket.userid;
listOfUsers[newUserId] = listOfUsers[oldUserId];
listOfUsers[newUserId].socket.userid = socket.userid = newUserId;
delete listOfUsers[oldUserId];
return;
}
socket.userid = newUserId;
listOfUsers[socket.userid] = {
socket: socket,
connectedWith: {},
isPublic: false,
extra: {}
};
} catch (e) {}
});
socket.on('set-password', function(password) {
try {
if (listOfUsers[socket.userid]) {
listOfUsers[socket.userid].password = password;
}
} catch (e) {}
});
socket.on('disconnect-with', function(remoteUserId, callback) {
try {
if (listOfUsers[socket.userid] && listOfUsers[socket.userid].connectedWith[remoteUserId]) {
delete listOfUsers[socket.userid].connectedWith[remoteUserId];
socket.emit('user-disconnected', remoteUserId);
}
if (!listOfUsers[remoteUserId]) return callback();
if (listOfUsers[remoteUserId].connectedWith[socket.userid]) {
delete listOfUsers[remoteUserId].connectedWith[socket.userid];
listOfUsers[remoteUserId].socket.emit('user-disconnected', socket.userid);
}
callback();
} catch (e) {}
});
function onMessageCallback(message) {
try {
if (!listOfUsers[message.sender]) {
socket.emit('user-not-found', message.sender);
return;
}
if (!listOfUsers[message.sender].connectedWith[message.remoteUserId] && !!listOfUsers[message.remoteUserId]) {
listOfUsers[message.sender].connectedWith[message.remoteUserId] = listOfUsers[message.remoteUserId].socket;
listOfUsers[message.sender].socket.emit('user-connected', message.remoteUserId);
if (!listOfUsers[message.remoteUserId]) {
listOfUsers[message.remoteUserId] = {
socket: null,
connectedWith: {},
isPublic: false,
extra: {}
};
}
listOfUsers[message.remoteUserId].connectedWith[message.sender] = socket;
if (listOfUsers[message.remoteUserId].socket) {
listOfUsers[message.remoteUserId].socket.emit('user-connected', message.sender);
}
}
if (listOfUsers[message.sender].connectedWith[message.remoteUserId] && listOfUsers[socket.userid]) {
message.extra = listOfUsers[socket.userid].extra;
listOfUsers[message.sender].connectedWith[message.remoteUserId].emit(socketMessageEvent, message);
}
} catch (e) {}
}
var numberOfPasswordTries = 0;
socket.on(socketMessageEvent, function(message, callback) {
if (message.remoteUserId && message.remoteUserId === socket.userid) {
// remoteUserId MUST be unique
return;
}
try {
if (message.remoteUserId && message.remoteUserId != 'system' && message.message.newParticipationRequest) {
if (listOfUsers[message.remoteUserId] && listOfUsers[message.remoteUserId].password) {
if (numberOfPasswordTries > 3) {
socket.emit('password-max-tries-over', message.remoteUserId);
return;
}
if (!message.password) {
numberOfPasswordTries++;
socket.emit('join-with-password', message.remoteUserId);
return;
}
if (message.password != listOfUsers[message.remoteUserId].password) {
numberOfPasswordTries++;
socket.emit('invalid-password', message.remoteUserId, message.password);
return;
}
}
}
if (message.message.shiftedModerationControl) {
if (!message.message.firedOnLeave) {
onMessageCallback(message);
return;
}
shiftedModerationControls[message.sender] = message;
return;
}
if (message.remoteUserId == 'system') {
if (message.message.detectPresence) {
if (message.message.userid === socket.userid) {
callback(false, socket.userid);
return;
}
callback(!!listOfUsers[message.message.userid], message.message.userid);
return;
}
}
if (!listOfUsers[message.sender]) {
listOfUsers[message.sender] = {
socket: socket,
connectedWith: {},
isPublic: false,
extra: {}
};
}
// if someone tries to join a person who is absent
if (message.message.newParticipationRequest) {
var waitFor = 120; // 2 minutes
var invokedTimes = 0;
(function repeater() {
invokedTimes++;
if (invokedTimes > waitFor) {
socket.emit('user-not-found', message.remoteUserId);
return;
}
if (listOfUsers[message.remoteUserId] && listOfUsers[message.remoteUserId].socket) {
onMessageCallback(message);
return;
}
setTimeout(repeater, 1000);
})();
return;
}
onMessageCallback(message);
} catch (e) {}
});
socket.on('disconnect', function() {
try {
var message = shiftedModerationControls[socket.userid];
if (message) {
delete shiftedModerationControls[message.userid];
onMessageCallback(message);
}
} catch (e) {}
try {
// inform all connected users
if (listOfUsers[socket.userid]) {
for (var s in listOfUsers[socket.userid].connectedWith) {
listOfUsers[socket.userid].connectedWith[s].emit('user-disconnected', socket.userid);
if (listOfUsers[s] && listOfUsers[s].connectedWith[socket.userid]) {
delete listOfUsers[s].connectedWith[socket.userid];
listOfUsers[s].socket.emit('user-disconnected', socket.userid);
}
}
}
} catch (e) {}
delete listOfUsers[socket.userid];
});
if (socketCallback) {
socketCallback(socket);
}
});
};
Anybody knows whats the fix?

You can either try Ahmed's solution i.e. passing server object here:
require('./Signaling-Server.js') (server);
In your codes, the server object is using http.
I'll suggest trying this instead:
var fs = require('fs');
var options = {
key: fs.readFileSync('fake-keys/privatekey.pem'),
cert: fs.readFileSync('fake-keys/certificate.pem')
};
var express = require("express"),
http = require("https"), // Use HTTPs here -------------
app = express(),
server = http.createServer(options, app);
require('./Signaling-Server.js')(server);
You can either try valid SSL certificate keys or fake-keys.
Here is how to use valid certificates:
var options = {
key: fs.readFileSync('../ssl/private/domain.com.key'),
cert: fs.readFileSync('../ssl/certs/domain.com.crt'),
ca: fs.readFileSync('../ssl/certs/domain.com.cabundle')
};

In Express 3, you should pass the app object to socket.io not the server like in Express 2. Assuming you are using Express 3 and not 2. You just need to change one line to set up socket.io correctly
Try replacing this
require('./Signaling-Server.js')(server);
with this
require('./Signaling-Server.js')(app);

Related

Socket.io Blocked loading mixed active content Error

I have a chat app i'm building, it works fine offline but in production, it refuses to connect and it gives out this error in the browser.
Blocked loading mixed active content
here is the code for the back end app.js
const http = require("http");
const express = require("express");
const app = express();
const path = require("path");
const server = http.createServer(app);
const dotenv = require("dotenv").config();
const router = require(path.join(__dirname + "/modules/router.js"));
const mongoose = require("mongoose");
const URL = process.env.DB_URL;
const Schema = require(path.join(__dirname + "/modules/Schema.js"));
const io = require("socket.io")(server, {
cors: {
origin: "*",
},
});
app.use(router);
mongoose.connect(URL, (err) => {
if (err) throw err;
else {
server.listen(process.env.PORT, console.log("Server is running"));
}
});
io.on("connection", (socket) => {
let payload = socket.handshake.auth.$token;
socket.emit("thru", true);
socket.on("join", async (link, cb) => {
// Checking users
Schema.Link.findOne({ code: link }, (err, d) => {
if (err || d == " ") cb(false, false);
else {
if (d.onlineUsers.length < 2) {
if (d.onlineUsers.includes(payload)) {
cb(true, true);
} else {
// Adding user
d.onlineUsers.unshift(payload);
Schema.Link.findOneAndUpdate(
{ code: link },
{ onlineUsers: d.onlineUsers },
(err, x) => {
if (err || x == "") cb(false, false);
else {
if (x.onlineUsers.length == 1) cb(true, true);
else cb(true, false);
}
}
);
}
} else cb(false, false);
}
});
socket.join(link);
socket.broadcast.to(link).emit("online", true);
socket.on("message", (m, cb) => {
m.date = new Date();
socket.broadcast.to(link).emit("broadcast", m);
cb(m);
});
});
socket.on("disconnect", (data) => {
const $link = socket.handshake.auth.$link;
Schema.Link.findOne({ code: $link })
.then((x) => {
if (x == "") console.log("user not found");
else {
let n = x.onlineUsers.filter((c) => c !== payload);
Schema.Link.findOneAndUpdate(
{ code: $link },
{ onlineUsers: n },
(err) => {
if (err) console.log(err);
else {
socket.broadcast.to($link).emit("online", false);
}
}
);
}
})
.catch((e) => {
console.log("Ending", e);
});
});
});
And here is the front end chat screen
useEffect(() => {
try {
socket.current = io("http://chatterbox-v2-api.vercel.app", {
auth: {
$token: localStorage.getItem("senders_token"),
$link: link,
},
});
} catch (err) {
console.log("Error");
}
i've tried hosting the scoket server on another platform but nothing.
I think the problem here is that you are trying to reach a HTTP server (http://chatterbox-v2-api.vercel.app) from a page served with HTTPS, which triggers an "Blocked loading mixed active content" error.
Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content
Is your server available with HTTPS (https://chatterbox-v2-api.vercel.app)?

How do I make sure socket.id is the same on the server and the client after a page reload?

I am writing a Proof Of Concept (for at least 2 months now) that uses Node cluster (workers), Redis and socket.io.
Socket.io is not in use for chat in this instance - just back to front communication. Ajax is not an option.
I am using pub/sub for redis and have that piece working (I think). At least the values returned from pubClient.get('key') are correct.
When I make a request from the front end and do not navigate or reload the page in any way, things work perfectly - I can make 10 requests and 10 responses are received.
Conversely, when I navigate, the same is not true - and I need to deliver the results no matter how much someone navigates on the front end.
It seems there is a disconnect after a reload. In both consoles - Dev Tools and node js, the socket ids are the same. I'm really scratching my head on this one!
Any help out there?
So, for some mainly socket.io code:
CLIENT:
socket = io('https://' + location.hostname + ':4444/', {
transports: ['websocket', 'polling'],
secure: true,
});
socket.on('download', function(data){// after reload, this never hits
console.log('DOWNLOAD '+ data.download);
});
var pkgs = ['y14Vfk617n6j', 'My77gWYmBLxT', 'IYd6dL9UoXkx'];
if(pkgs.length > 0){
for(var i = 0; i < pkgs.length; i++){
socket.emit('get-request', pkgs[i]);
}
}
SERVER:
var cluster = require('cluster');
var express = require('express');
var numCPUs = require('os').cpus().length;
const { setupMaster, setupWorker } = require("#socket.io/sticky");
const { createAdapter, setupPrimary } = require("#socket.io/cluster-adapter");
var app = express();
const https = require('https');
const { Server } = require("socket.io");
const Redis = require("ioredis");
const sock_nodes = [
{port: 6379, host: '192.168.0.41'},
{port: 6380, host: '192.168.0.34'},
{port: 6381, host: '192.168.0.35'},
{port: 6379, host: '192.168.0.34'},
{port: 6380, host: '192.168.0.35'},
{port: 6381, host: '192.168.0.41'}
];
const port = 4444;
const httpServer = https.createServer(options, app);
const io = new Server(httpServer, {maxHttpBufferSize: 10240000});
const pubClient = new Redis.Cluster(sock_nodes, {
redisOptions: {
password: 'my secret!'
}
});
const subClient = pubClient.duplicate(); // I am not actually using this - should I be?
if (cluster.isMaster) {
for (var i = 0; i < numCPUs; i++) {
// Create a worker
cluster.fork();
}
cluster.on("exit", (worker) => {
console.log(`Worker PID ${worker.process.pid} died`);
var w = cluster.fork();
console.log('WORKER %d died (%s). restarting...', worker.process.pid, worker.state);
w.on('message', function(msg){
console.log("Message Received : " , msg);
});
});
} else {
app.use((req, res, next) => {
var reqip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
//~ console.log(reqip, md5(reqip));
var sess = parseCookies(req, 'session_state');
if(!sess){
res.cookie('session_state', md5(reqip));
}
next();
});
app.get('/', (req, res) => {
getSession(req, res, function(sess){
getPub('currSockets', sess, function(err, socket){
res.render("pages/shared/index", {'ns': sess, 'socket': socket});
});
});
});
});
app.get('/start', function(req, res){
getSession(req, res, function(sess){
getPub('currSockets', sess, function(err, socket){
res.render("pages/shared/start", {'ns': sess, 'socket': socket});
});
});
});
io.on('connection', function (socket) {
var currUser = parseCookies(socket.request, 'session_state');
socket.join(currUser);
getPub('currSockets', currUser, function(err, currSockets){
if (currSockets) {
currSockets = JSON.parse(currSockets);
if (currSockets[currUser]) {
if (currSockets[currUser].stream) {
currSockets[currUser].sock = socket.id;
setCurrSockets(currSockets, currUser, null, function(cSocks){
});
}
}
}
});
socket.on('get-request', function(data){ // can be one or many requests
// there is a similar, currently irrelevant, socket.on('new-request') that is left out here
if(data){
getPub('currSockets', currUser, function(err, currSockets){
currSockets = JSON.parse(currSockets);
if(currSockets){
if(currUser){
if(currSockets[currUser]){
if(currSockets[currUser].stream){
var str = Object.keys(currSockets[currUser].stream);
for(var i = 0; i < str.length; i++){
if(str[i] !== 'sock'){
if(!currSockets[currUser].stream[str[i]]){
delete currSockets[currUser].stream[str[i]];
setCurrSockets(currSockets, currUser, null, function(cSocks){
checkCurrSockets(currUser, data, socket);
});
}
}
}
}
}
}
}
});
}
});
});
httpServer.listen(port, () => {
logs(__line__, `Worker ${process.pid} listening on ${port}`);
});
}
function existsPub(key, cb){
return pubClient.exists(key, cb);
}
function setPub(key, val, cb){
if(val === JSON.stringify({})){
return pubClient.get(key, cb);
}
return pubClient.set(key, val, cb);
}
function getPub(key, currUser, cb){
existsPub(key, function(err, reply){
if(reply === 1){
return pubClient.get(key, cb);// always getting an old socket.id
}
});
}
// Here is the piece that doesn't work after reloading the page
function ioEmit (currSock, target, payload) {
io.to(currSock).emit(target, payload); // doesn't work after page reload
}
// end piece where after reload does not work
getPub('currSockets', currUser, function(err, currSockets){
if( currSockets){
currSockets = JSON.parse(currSockets);
ioEmit(currUser, 'download', {'download': currSockets[currUser].stream[data]);
}
});
function parseCookies (req, name) {
var list = {}, rc;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list[name];
}
function getSession(req, res, callback) {
var sess = false;
if(req.headers) {// handle req
var reqip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
if(req.headers.cookie){
sess = req.headers.cookie.split('=')[1].split(';')[0];
} else {
res.cookie('session_state', md5(reqip));
}
return callback(sess);
} else if(req.request) {// handle socket
//~ console.log('req.request.headers.cookie', req.request.headers.cookie.split('=')[1]);
if(req.request.headers.cookie){
sess = req.request.headers.cookie.split('=')[1].split(';')[0];
//~ req.emit('join', sess);
//~ callback({[sess]: {'sock': req.id}});
callback(req.id);
}
} else {
return callback(null);
}
}
function setCurrSockets(currSockets, currUser, data, cb){
if(Object.keys(currSockets[currUser].stream).length > 0){
if(data){
if(ready(currSockets, currUser, data)){
delete currSockets[currUser].stream[data];// it appears that setCurrSockets is getting called too soon
}
}
setPub('currSockets', JSON.stringify(currSockets), function(err){
});
if(typeof cb === 'function'){
setTimeout(() => {
getPub('currSockets', currUser, function(err, cSocks){
cb(cSocks);// updated callback to return cSocks
}, 2000);
});
}
} else {
currSockets[currUser].stream = {};
setPub('currSockets', JSON.stringify(currSockets), function(err){
if(err){
} else {
if(typeof cb === 'function'){
cb(currSockets);// updated callback to return cSocks
}
}
});
}
}
figured this out. The problem was in here:
for(var i = 0; i < str.length; i++){
if(str[i] !== 'sock'){
>>>> if(!currSockets[currUser].stream[str[i]]){ // never true
// delete currSockets[currUser].stream[str[i]];
setCurrSockets(currSockets, currUser, null, function(cSocks){
checkCurrSockets(currUser, data, socket);
});
}
}
}
so I commented the for loop and kept the setCurrSockets part and it works.
Just thought I would share, in case someone else tries to use redis, node cluster and socket.io together. As #jfreind00 said, you should use an authentication system with a randomly gen'd string for storing cookies.

Node.js webRTC screen shareing

I have got problem with webRTC screen sharing. When one person shares his screen another person can`t see shared screen stream, and asks him for again sharing screen.I am useing node.js express server with socket.io. I am useing Google chrome. It requires HTTPS connection if it is not local.
This is web application code`
(function() {
const socket = io.connect(window.location.origin);
const localVideo = document.querySelector('.localVideo');
const remoteVideos = document.querySelector('.remoteVideos');
const peerConnections = {};
var url_string =window.location.href
var url = new URL(url_string);
var de = url.searchParams.get("key");
let room = de
let getUserMediaAttempts = 5;
let gettingUserMedia = false;
let getdisplaymedia=true;
const config = {
'iceServers': [{
'urls': ['stun:stun.l.google.com:19302']
}]
};
/** #type {MediaStreamConstraints} */
const constraints = {
audio: true,
video: { facingMode: "user" }
};
socket.on('bye', function(id) {
handleRemoteHangup(id);
});
if (room && !!room) {
socket.emit('join', room);
}
window.onunload = window.onbeforeunload = function() {
socket.close();
};
socket.on('ready', function (id) {
if (!(localVideo instanceof HTMLVideoElement) || !localVideo.srcObject) {
return;
}
const peerConnection = new RTCPeerConnection(config);
peerConnections[id] = peerConnection;
if (localVideo instanceof HTMLVideoElement) {
peerConnection.addStream(localVideo.srcObject);
}
peerConnection.createOffer()
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(function () {
socket.emit('offer', id, peerConnection.localDescription);
});
peerConnection.onaddstream = event => handleRemoteStreamAdded(event.stream, id);
peerConnection.onicecandidate = function(event) {
if (event.candidate) {
socket.emit('candidate', id, event.candidate);
}
};
});
socket.on('offer', function(id, description) {
const peerConnection = new RTCPeerConnection(config);
peerConnections[id] = peerConnection;
if (localVideo instanceof HTMLVideoElement) {
peerConnection.addStream(localVideo.srcObject);
}
peerConnection.setRemoteDescription(description)
.then(() => peerConnection.createAnswer())
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(function () {
socket.emit('answer', id, peerConnection.localDescription);
});
peerConnection.onaddstream = event => handleRemoteStreamAdded(event.stream, id);
peerConnection.onicecandidate = function(event) {
if (event.candidate) {
socket.emit('candidate', id, event.candidate);
}
};
});
socket.on('candidate', function(id, candidate) {
peerConnections[id].addIceCandidate(new RTCIceCandidate(candidate))
.catch(e => console.error(e));
});
socket.on('answer', function(id, description) {
peerConnections[id].setRemoteDescription(description);
});
function getUserMediaSuccess(stream) {
gettingUserMedia = false;
if (localVideo instanceof HTMLVideoElement) {
!localVideo.srcObject && (localVideo.srcObject = stream);
}
socket.emit('ready');
}
function handleRemoteStreamAdded(stream, id) {
const remoteVideo = document.createElement('video');
remoteVideo.srcObject = stream;
remoteVideo.setAttribute("id", id.replace(/[^a-zA-Z]+/g, "").toLowerCase());
remoteVideo.setAttribute("playsinline", "true");
remoteVideo.setAttribute("autoplay", "true");
remoteVideos.appendChild(remoteVideo);
if (remoteVideos.querySelectorAll("video").length === 1) {
remoteVideos.setAttribute("class", "one remoteVideos");
} else {
remoteVideos.setAttribute("class", "remoteVideos");
}
}
function getUserMediaError(error) {
console.error(error);
gettingUserMedia = false;
(--getUserMediaAttempts > 0) && setTimeout(getUserMediaDevices, 1000);
}
function getUserMediaDevices() {
if (localVideo instanceof HTMLVideoElement) {
if (localVideo.srcObject) {
getUserMediaSuccess(localVideo.srcObject);
} else if (!gettingUserMedia && !localVideo.srcObject) {
gettingUserMedia = true;
navigator.mediaDevices.getDisplayMedia(constraints)
.then(getUserMediaSuccess)
.catch(getUserMediaError);
}
}
}
function handleRemoteHangup(id) {
peerConnections[id] && peerConnections[id].close();
delete peerConnections[id];
document.querySelector("#" + id.replace(/[^a-zA-Z]+/g, "").toLowerCase()).remove();
if (remoteVideos.querySelectorAll("video").length === 1) {
remoteVideos.setAttribute("class", "one remoteVideos");
} else {
remoteVideos.setAttribute("class", "remoteVideos");
}
}
getUserMediaDevices();
})();
This is node.js code`
const credentials = require('./credentials');
const express = require('express');
const app = express();
let server;
let port;
if (credentials.key && credentials.cert) {
const https = require('https');
server = https.createServer(credentials, app);
port = 443;
} else {
const http = require('http');
server = http.createServer(app);
port = 1517;
}
const io = require('socket.io')(server);
const RoomService = require('./RoomService')(io);
io.sockets.on('connection', RoomService.listen);
io.sockets.on('error', e => console.log(e));
app.use(express.static(__dirname + '/public'));
app.get('*', function(req, res) {
res.sendFile(${__dirname}/public/index.html);
});
server.listen(port, () => console.log(Server is running on port ${port}));
ok man this is fixed code you can use yuu need just stream getDisplayMedia value
(function() {
const socket = io.connect(window.location.origin);
const localVideo = document.querySelector('.localVideo');
const remoteVideos = document.querySelector('.remoteVideos');
const peerConnections = {};
var url_string =window.location.href
var url = new URL(url_string);
var de = url.searchParams.get("key");
let room = de
let getUserMediaAttempts = 5;
let gettingUserMedia = false;
let getdisplaymedia=true;
/** #type {RTCConfiguration} */
const config = {
'iceServers': [{
'urls': ['stun:stun.l.google.com:19302']
}]
};
/** #type {MediaStreamConstraints} */
const constraints = {
audio: true,
video: { facingMode: "user" }
};
socket.on('full', function(room) {
alert('Room ' + room + ' is full');
});
socket.on('bye', function(id) {
handleRemoteHangup(id);
});
if (room && !!room) {
socket.emit('join', room);
}
window.onunload = window.onbeforeunload = function() {
socket.close();
};
socket.on('ready', function (id) {
if (!(localVideo instanceof HTMLVideoElement) || !localVideo.srcObject) {
return;
}
const peerConnection = new RTCPeerConnection(config);
peerConnections[id] = peerConnection;
if (localVideo instanceof HTMLVideoElement) {
peerConnection.addStream(localVideo.srcObject);
}
peerConnection.createOffer()
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(function () {
socket.emit('offer', id, peerConnection.localDescription);
});
peerConnection.onaddstream = event => handleRemoteStreamAdded(event.stream, id);
peerConnection.onicecandidate = function(event) {
if (event.candidate) {
socket.emit('candidate', id, event.candidate);
}
};
});
socket.on('offer', function(id, description) {
const peerConnection = new RTCPeerConnection(config);
peerConnections[id] = peerConnection;
if (localVideo instanceof HTMLVideoElement) {
peerConnection.addStream(localVideo.srcObject);
}
peerConnection.setRemoteDescription(description)
.then(() => peerConnection.createAnswer())
.then(sdp => peerConnection.setLocalDescription(sdp))
.then(function () {
socket.emit('answer', id, peerConnection.localDescription);
});
peerConnection.onaddstream = event => handleRemoteStreamAdded(event.stream, id);
peerConnection.onicecandidate = function(event) {
if (event.candidate) {
socket.emit('candidate', id, event.candidate);
}
};
});
socket.on('candidate', function(id, candidate) {
peerConnections[id].addIceCandidate(new RTCIceCandidate(candidate))
.catch(e => console.error(e));
});
socket.on('answer', function(id, description) {
peerConnections[id].setRemoteDescription(description);
});
function getUserMediaSuccess(stream) {
gettingUserMedia = false;
if (localVideo instanceof HTMLVideoElement) {
!localVideo.srcObject && (localVideo.srcObject = stream);
}
socket.emit('ready');
}
function handleRemoteStreamAdded(stream, id) {
const remoteVideo = document.createElement('video');
remoteVideo.srcObject = stream;
remoteVideo.setAttribute("id", id.replace(/[^a-zA-Z]+/g, "").toLowerCase());
remoteVideo.setAttribute("playsinline", "true");
remoteVideo.setAttribute("autoplay", "true");
remoteVideos.appendChild(remoteVideo);
if (remoteVideos.querySelectorAll("video").length === 1) {
remoteVideos.setAttribute("class", "one remoteVideos");
} else {
remoteVideos.setAttribute("class", "remoteVideos");
}
}
function getUserMediaError(error) {
console.error(error);
gettingUserMedia = false;
(--getUserMediaAttempts > 0) && setTimeout(getUserMediaDevices, 1000);
}
function getUserMediaDevices() {
var constraints = { audio: true, video: { width: 1280, height: 720 } };
navigator.mediaDevices.getDisplayMedia(constraints)
.then(function(mediaStream) {
var video = document.querySelector('video');
video.srcObject = mediaStream;
video.onloadedmetadata = function(e) {
video.play();
getUserMediaSuccess(video.srcObject)
};
})
.catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end.
}
function handleRemoteHangup(id) {
peerConnections[id] && peerConnections[id].close();
delete peerConnections[id];
document.querySelector("#" + id.replace(/[^a-zA-Z]+/g, "").toLowerCase()).remove();
if (remoteVideos.querySelectorAll("video").length === 1) {
remoteVideos.setAttribute("class", "one remoteVideos");
} else {
remoteVideos.setAttribute("class", "remoteVideos");
}
}
getUserMediaDevices();
})();

Hijack response before sent to client

I have follow codes to be used as middlewares
module.exports=function(callback) {
callbacks.push(callback);
return function(req,res,next) {
if (!res.hijacked) {
res.hijacked=true;
} else {
return next();
}
var send=res.send;
res.send=function(data) {
var body=data instanceof Buffer ? data.toString() : data;
var requests=[];
requests.push(function(next) {
callbacks[0](req,res)(body,doneWrapper(body,next));
});
for (var i=1;i<callbacks.length;i++) {
var hijackCallback=callbacks[i];
requests.push(function(result,next) {
hijackCallback(req,res)(result,doneWrapper(result,next));
});
}
var that=this;
async.waterfall(requests,function(err,result) {
send.call(that,result);
requests=null;
body=null;
that=null;
});
};
next();
};
};
An example of usage is as following:
module.exports=function() {
return hijack(function() {
return function(result,done) {
var json={};
try {
json=JSON.parse(result);
} catch(e) {
return done();
}
if (!_.isArray(json)) {
return done();
}
var sorted=_(json).sortBy(function(item) {
if (_.isObject(item.information)) {
return item.information.rangeIndex1 || 999;
} else {
return 1001;
}
});
done(sorted);
}
});
};
It worked fine initially as middlewares in routes.
However,When i try to make it as app.use(hijackMiddleware()). Something went wrong, I got this Can't set headers after they are sent error.
There is no problem when used as middlewares in routes,though.
Have you consider using express-interceptor? Is really easy to use:
var express = require('express');
var cheerio = require('cheerio');
var interceptor = require('express-interceptor');
var app = express();
var finalParagraphInterceptor = interceptor(function(req, res){
return {
// Only HTML responses will be intercepted
isInterceptable: function(){
return /text\/html/.test(res.get('Content-Type'));
},
// Appends a paragraph at the end of the response body
intercept: function(body, send) {
var $document = cheerio.load(body);
$document('body').append('<p>From interceptor!</p>');
send($document.html());
}
};
})
// Add the interceptor middleware
app.use(finalParagraphInterceptor);
app.use(express.static(__dirname + '/public/'));
app.listen(3000);

WebRTC: One to one Audio call not working in different machine

I am trying to implement a one to one audio call using webRTC (signalling using websockets) . But it works when i try it in one system using multiple tabs of chrome (localhost). When I try to hit my server from another machine it does initial handshakes , but call doesn't happen.
But when i try to change the tag to and changed the constraints to video constraints . it works even if the we try to access from other machine (i.e video call works ).
I initially thought it was because if firewall but when video call worked I was puzzled .
Here is my code:
// Constraints to get audio stream only
$scope.constraints = {
audio: {
mandatory: {
googEchoCancellation: true
},
optional: []
},
video:false
};
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
// success Callback of getUserMedia(), stream variable is the audio stream.
$scope.successCallback = function (stream) {
if (window.URL) {
myVideo.src = window.URL.createObjectURL(stream); // converting media stream to Blob URL.
} else {
myVideo.src = stream;
}
//attachMediaStream(audioTag, stream);
localStream = stream;
if (initiator)
maybeStart();
else
doAnswer();
};
// failure Callback of getUserMedia()
$scope.failureCallback = function (error) {
console.log('navigator.getUserMedia Failed: ', error);
};
var initiator, started = false;
$("#call").click(function () {
socket.emit("message", undefined);
initiator = true;
navigator.getUserMedia($scope.constraints, $scope.successCallback, $scope.failureCallback);
});
var channelReady = false;
socket.on('message', function (data) {
channelReady = true;
if (data) {
if (data.type === 'offer') {
if (!initiator) {
$("#acceptCall").show();
$("#acceptCall").click(function(){
if (!initiator && !started) {
var pc_config = {
iceServers: [
{ url: "stun:stun.l.google.com:19302" },
{ url: "turn:numb.viagenie.ca", credential: "drfunk", username: "toadums#hotmail.com"}
]
};
pc = new webkitRTCPeerConnection(pc_config);
pc.onicecandidate = onIceCandidate;
pc.onaddstream = onRemoteStreamAdded;
}
pc.setRemoteDescription(new RTCSessionDescription(data));
$scope.acceptCall();
});
}
} else if (data.type === 'answer' && started) {
pc.onaddstream = onRemoteStreamAdded;
pc.setRemoteDescription(new RTCSessionDescription(data));
} else if (data.type === 'candidate' && started) {
var candidate = new RTCIceCandidate({
sdpMLineIndex: data.label,
candidate: data.candidate
});
pc.addIceCandidate(candidate);
} else if (data.type === 'bye' && started) {
console.log("Bye");
}
}
});
function onRemoteStreamAdded(event) {
othersVideo.src = URL.createObjectURL(event.stream);
};
var sdpConstraints = {
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': false
}
};
function doAnswer() {
pc.addStream(localStream);
pc.createAnswer(gotDescription,null,sdpConstraints);
}
function gotDescription(desc) {
pc.setLocalDescription(desc);
socket.send(desc);
}
function maybeStart() {
if (!started && localStream && channelReady)
createPeerConnection();
pc.addStream(localStream);
started = true;
if (initiator)
doCall();
}
$scope.acceptCall = function () {
navigator.getUserMedia($scope.constraints, $scope.successCallback, $scope.failureCallback);
}
function createPeerConnection() {
var pc_config = {
iceServers: [
{ url: "stun:stun.l.google.com:19302" },
{ url: "turn:numb.viagenie.ca", credential: "drfunk", username: "toadums#hotmail.com"}
]
};
pc = new webkitRTCPeerConnection(pc_config);
pc.onicecandidate = onIceCandidate;
console.log("Created RTCPeerConnnection with config:\n" + " \"" +
JSON.stringify(pc_config) + "\".");
};
function doCall() {
$scope.caller = true;
pc.createOffer(setLocalAndSendMessage,null,sdpConstraints);
};
function setLocalAndSendMessage(sessionDescription) {
pc.setLocalDescription(sessionDescription);
socket.send(sessionDescription);
}
function onIceCandidate(event) {
if (event.candidate) {
socket.emit('message', {
type: 'candidate',
label: event.candidate.sdpMLineIndex,
id: event.candidate.sdpMid,
candidate: event.candidate.candidate
});
} else {
console.log("End of candidates.");
}
}
If navigator.mediaDevices is undefined, this because work only in secure context (https)
see:
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia

Resources