Hello there i am integrating Wowza Media Server with Temasys plugin(for crossbrowser support) and the code runs great on Chrome but on IE11+ its is giving me network error.Please see attached image and code for details.
const GO_BUTTON_START = "Publish";
const GO_BUTTON_STOP = "Stop";
var video = document.querySelector('video');
var peerConnection = null;
var peerConnectionConfig = {'iceServers': []};
var localStream = null;
var wsURL = "wss://localhost.streamlock.net/webrtc-session.json";
var wsConnection = null;
var streamInfo = {applicationName:"webrtc", streamName:"myStream", sessionId:"[empty]"};
var userData = {param1:"value1"};
var videoBitrate = 360;
var audioBitrate = 64;
var newAPI = false;
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
window.RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate || window.webkitRTCIceCandidate;
window.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.webkitRTCSessionDescription;
//var constraints = {
//audio: false,
//video: true
//};
function successCallback(stream) {
window.stream = stream; // make stream available to browser console
localStream=stream;
console.log(localStream);
video = attachMediaStream(video, stream);
}
function errorCallback(error) {
console.log('navigator.getUserMedia error: ', error);
}
function pageReady()
{
$("#buttonGo").attr('value', GO_BUTTON_START);
var constraints =
{
video: true,
audio: false,
};
//alert('here');
navigator.getUserMedia(constraints, successCallback, errorCallback);
console.log("newAPI: "+newAPI);
}
function wsConnect(url)
{
wsConnection = new WebSocket(url);
wsConnection.binaryType = 'arraybuffer';
wsConnection.onopen = function()
{
console.log("wsConnection.onopen");
peerConnection = new RTCPeerConnection(peerConnectionConfig);
peerConnection.onicecandidate = gotIceCandidate;
if (newAPI)
{
var localTracks = localStream.getTracks();
for(localTrack in localTracks)
{
console.log("video stream"+localStream);
peerConnection.addTrack(localTracks[localTrack], localStream);
}
}
else
{
console.log("video stream"+localStream);
peerConnection.addStream(localStream);
}
peerConnection.createOffer(gotDescription, errorHandler);
}
wsConnection.onmessage = function(evt)
{
console.log("wsConnection.onmessage: "+evt.data);
var msgJSON = JSON.parse(evt.data);
var msgStatus = Number(msgJSON['status']);
var msgCommand = msgJSON['command'];
if (msgStatus != 200)
{
$("#sdpDataTag").html(msgJSON['statusDescription']);
stopPublisher();
}
else
{
$("#sdpDataTag").html("");
var sdpData = msgJSON['sdp'];
if (sdpData !== undefined)
{
console.log('sdp: '+msgJSON['sdp']);
peerConnection.setRemoteDescription(new RTCSessionDescription(sdpData), function() {
//peerConnection.createAnswer(gotDescription, errorHandler);
}, errorHandler);
}
var iceCandidates = msgJSON['iceCandidates'];
if (iceCandidates !== undefined)
{
for(var index in iceCandidates)
{
console.log('iceCandidates: '+iceCandidates[index]);
peerConnection.addIceCandidate(new RTCIceCandidate(iceCandidates[index]));
}
}
}
if (wsConnection != null)
wsConnection.close();
wsConnection = null;
}
wsConnection.onclose = function(error)
{
console.log("wsConnection.onclose"+error);
}
wsConnection.onerror = function(evt)
{
console.log("wsConnection.onerror: "+JSON.stringify(evt));
$("#sdpDataTag").html('WebSocket connection failed: '+wsURL);
stopPublisher();
}
}
function startPublisher()
{
wsURL = $('#sdpURL').val();
streamInfo.applicationName = $('#applicationName').val();
streamInfo.streamName = $('#streamName').val();
videoBitrate = $('#videoBitrate').val();
audioBitrate = $('#audioBitrate').val();
$.cookie("webrtcPublishWSURL", wsURL, { expires: 365 });
$.cookie("webrtcPublishApplicationName", streamInfo.applicationName, { expires: 365 });
$.cookie("webrtcPublishStreamName", streamInfo.streamName, { expires: 365 });
$.cookie("webrtcPublishVideoBitrate", videoBitrate, { expires: 365 });
$.cookie("webrtcPublishAudioBitrate", audioBitrate, { expires: 365 });
console.log("startPublisher: wsURL:"+wsURL+" streamInfo:"+JSON.stringify(streamInfo));
wsConnect(wsURL);
$("#buttonGo").attr('value', GO_BUTTON_STOP);
}
function stopPublisher()
{
if (peerConnection != null)
peerConnection.close();
peerConnection = null;
if (wsConnection != null)
wsConnection.close();
wsConnection = null;
$("#buttonGo").attr('value', GO_BUTTON_START);
console.log("stopPublisher");
}
function btn_start()
{
alert('button clicked');
if (peerConnection == null)
startPublisher();
else
stopPublisher();
}
function gotIceCandidate(event)
{
if(event.candidate != null)
{
//console.log('gotIceCandidate: '+JSON.stringify({'ice': event.candidate}));
}
}
function gotDescription(description)
{
var enhanceData = new Object();
if (audioBitrate !== undefined)
enhanceData.audioBitrate = Number(audioBitrate);
if (videoBitrate !== undefined)
enhanceData.videoBitrate = Number(videoBitrate);
description.sdp = enhanceSDP(description.sdp, enhanceData);
console.log('gotDescription: '+JSON.stringify({'sdp': description}));
peerConnection.setLocalDescription(description, function () {
wsConnection.send('{"direction":"publish", "command":"sendOffer", "streamInfo":'+JSON.stringify(streamInfo)+', "sdp":'+JSON.stringify(description)+', "userData":'+JSON.stringify(userData)+'}');
console.log("stream info"+JSON.stringify(streamInfo));
console.log("stream description"+JSON.stringify(description));
console.log("stream userData"+JSON.stringify(userData));
}, function() {console.log('set description error')});
}
function enhanceSDP(sdpStr, enhanceData)
{
var sdpLines = sdpStr.split(/\r\n/);
var sdpSection = 'header';
var hitMID = false;
var sdpStrRet = '';
for(var sdpIndex in sdpLines)
{
var sdpLine = sdpLines[sdpIndex];
if (sdpLine.length <= 0)
continue;
sdpStrRet += sdpLine+'\r\n';
if (sdpLine.indexOf("m=audio") === 0)
{
sdpSection = 'audio';
hitMID = false;
}
else if (sdpLine.indexOf("m=video") === 0)
{
sdpSection = 'video';
hitMID = false;
}
if (sdpLine.indexOf("a=mid:") === 0)
{
if (!hitMID)
{
if ('audio'.localeCompare(sdpSection) == 0)
{
if (enhanceData.audioBitrate !== undefined)
{
sdpStrRet += 'b=AS:' + enhanceData.audioBitrate + '\r\n';
sdpStrRet += 'b=TIAS:' + (enhanceData.audioBitrate*1024) + '\r\n';
}
}
else if ('video'.localeCompare(sdpSection) == 0)
{
if (enhanceData.videoBitrate !== undefined)
{
sdpStrRet += 'b=AS:' + enhanceData.videoBitrate + '\r\n';
sdpStrRet += 'b=TIAS:' + (enhanceData.videoBitrate*1024) + '\r\n';
}
}
hitMID = true;
}
}
}
return sdpStrRet;
}
function errorHandler(error)
{
console.log(error);
}
Click here to see image
Related
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();
})();
I am new to nodejs so below is my code, I need to add try-catch blocks for my below code need some help to do this because new to this things, below is my websocket code newly created I need to add try-catch blocks for this , please help me out anyone
var WebSocket = require('ws');
//var Stomp = require('stompjs');
function CustomWebSocketListener(config) {
RED.nodes.createNode(this,config);
var node = this;
node.on('input', function(msg) {
let temp =msg.payload;
let urllist = temp.url;
let urls=[]
if(global.websocket!=null || global.websocket!=undefined){
let connections=global.websocket;
console.log("global")
if(global.isAccessTokenExpired){
for(let k in connections) {
connections[k].close();
connections[k].reconnect=false
console.log('connection closed:::');
}
urls=urllist;
}
else{
for(let i=0;i<urllist.length;i++){
let group=urllist[i].split("/")[7].split("?");
if(!connections[group[0]]){
urls.push(urllist[i])
}
}
}
}
else{
urls=urllist;
}
console.log("urls.length::::"+urls.length)
if(urls.length > 0){
for(let i=0;i<urls.length;i++){
console.log(':::::::for loop:::::::')
console.log('url----'+urls[i])
function connect(urlIndex) {
let ws;
if(urlIndex!=undefined||urlIndex!=null){
ws = new WebSocket(urls[urlIndex]);
}
else{
ws = new WebSocket(urls[i]);
}
ws.index=i;
ws.reconnect=true;
ws.onopen = function() {
};
ws.onmessage = function(e) {
console.log('Message:', e.data);
console.log('Socket is closed. Reconnect will be attempted in 30 second.', e.reason);
setTimeout(function() {
console.log("onclose ----ws reconnect"+ws.reconnect)
if(ws.reconnect){
console.log("inside if reconnect")
connect(ws.index);
}
}, 30000);
};
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
if(global.websocket==null || global.websocket==undefined){
global.websocket={};
console.log(global.websocket)
global.websocket[urls[i]]=ws;
}
else{
global.websocket[urls[i]]=ws;
}
}
connect();
}
}
});
}
RED.nodes.registerType("custom-websocketlistener",CustomWebSocketListener);
}
Thanks for anyone who would help me out with this
you can directly use where you want like this...
try{
//whatever you want
}
catch(e){
//whatever you want
}
In your code you can use like this
try {
RED.nodes.createNode(this, config)
var node = this
node.on('input', function(msg) {
let temp = msg.payload
let urllist = temp.url
let urls = []
if (global.websocket != null || global.websocket != undefined) {
let connections = global.websocket
console.log('global')
if (global.isAccessTokenExpired) {
for (let k in connections) {
connections[k].close()
connections[k].reconnect = false
console.log('connection closed:::')
}
urls = urllist
} else {
for (let i = 0; i < urllist.length; i++) {
let group = urllist[i].split('/')[7].split('?')
if (!connections[group[0]]) {
urls.push(urllist[i])
}
}
}
} else {
urls = urllist
}
console.log('urls.length::::' + urls.length)
if (urls.length > 0) {
for (let i = 0; i < urls.length; i++) {
console.log(':::::::for loop:::::::')
console.log('url----' + urls[i])
function connect(urlIndex) {
let ws
if (urlIndex != undefined || urlIndex != null) {
ws = new WebSocket(urls[urlIndex])
} else {
ws = new WebSocket(urls[i])
}
ws.index = i
ws.reconnect = true
ws.onopen = function() {}
ws.onmessage = function(e) {
console.log('Message:', e.data)
console.log('Socket is closed. Reconnect will be attempted in 30 second.', e.reason)
setTimeout(function() {
console.log('onclose ----ws reconnect' + ws.reconnect)
if (ws.reconnect) {
console.log('inside if reconnect')
connect(ws.index)
}
}, 30000)
}
ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket')
ws.close()
}
if (global.websocket == null || global.websocket == undefined) {
global.websocket = {}
console.log(global.websocket)
global.websocket[urls[i]] = ws
} else {
global.websocket[urls[i]] = ws
}
}
connect()
}
}
})
} catch (e) {
console.log(e)
}
}
I have the following piece of code which is working fine.
var config = require('./config');
var cheerio = require('cheerio');
var myhttp = require('./myHttp');
var stringHelper = require('./stringHelper');
var Base64 = require('./base64.js').Base64;
var Encrypt = require('./Encrypt.js');
var myEncode = require('./Encode.js');
var rules = require('./rules');
var io = require('socket.io-emitter')({ host: '127.0.0.1', port: 6379 });
var mysql = require('mysql');
delete require.cache[require.resolve('./requestLogin1.js')]
var myvar = require('./requestLogin1.js');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : 'abc',
database : 'abcd'
}
);
connection.connect(function(err) {
if (err) {
console.log('error connecting: ' + err.stack);
return;
}
});
var timerOB;
var timerMW;
var timerP;
var timerTL;
var news = {
'mw': [],
'ob': [],
'all': {},
};
var status = false;
function round(rnum, rlength) {
return newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
}
function roundup(rnum, rlength) {
return newnumber = Math.ceil(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
}
function rounddown(rnum, rlength) {
return newnumber = Math.floor(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
}
function function1(_html) {
console.log('function1 run')
var $ = cheerio.load(_html);
var v_lgnid = $('#userId').attr('value');
var v_psswrd = config.password;
var v_data = v_lgnid + "|" + v_psswrd;
var _key = $('#accntid').attr('value');
if (_key) {
v_data = Base64.encode(Encrypt.AESEncryptCtr(v_data, _key , "256"));
v_data = escape(v_data);
myhttp.get(
'https://example.com/ValidPassword.jsp?' + $('#name').attr('value') + "=" + v_data,
function (_htmlShowImage) {
if (_htmlShowImage && _htmlShowImage.trim() == "OK") {
function2();
} else {
console.log('Login Fail');
}
});
} else {
login();
console.log('Encrypt password error');
}
}
function function2() {
myhttp.get(
'https://example.com/QuestionsAuth.jsp',
function (_htmlShowImage) {
var $ = cheerio.load(_htmlShowImage);
var sLoginID = $('#sLoginID').attr('value');
var Answer1 = config.answer1;
var Answer2 = config.answer2;
var Index1 = $('#st1').attr('value');
var Index2 = $('#st2').attr('value');
var v_data = sLoginID + "|" + Answer1 + "|" + Answer2 + "|" + Index1 + "|" + Index2;
v_data = Base64.encode(Encrypt.AESEncryptCtr(v_data, $('#key_questauth').attr('value'), "256"));
v_data = escape(v_data);
myhttp.get(
'https://example.com/ValidAnswers.jsp?' + $('#name_questauth').attr('value') + "=" + v_data,
function (_htmlShowImage) {
if (_htmlShowImage && _htmlShowImage.trim() == "OK") {
//rootCallback();
myhttp.get(
'https://example.com/DefaultLogin.jsp',
function (_html) {
console.log('Login sucess')
stringHelper.SaveFileCookies('abcd.txt', myhttp.loadCookie(), 'save cookie login sucess');
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
if (timerOB) {
clearTimeout(timerOB);
}
timerOB = setTimeout(function5, config.DelayExtractOB);
if (timerP) {
clearTimeout(timerP);
}
timerP = setTimeout(function4, config.function4);
});
} else {
console.log('Login Fail - timer');
}
});
});
}
var login = function () {
if (timerMW) {
clearTimeout(timerMW);
}
if (timerOB) {
clearTimeout(timerOB);
}
if (timerP) {
clearTimeout(timerP);
}
if (timerTL) {
clearTimeout(timerTL);
}
myhttp.init();
myhttp.post(
'https://example.com/ShowImage.jsp',
{ "requiredLogin": myEncode.Convert(config.uname) },
function (_htmlpost) {
if (_htmlpost) {
function1(_htmlpost);
} else {
if (timerTL) {
clearTimeout(timerTL);
}
timerTL = setTimeout(login, config.DelayNestError);
}
});
}
exports.login = login;
function function3() {
return {
TS: '',
MWP: 0,
LTP: 0,
NQ: 0,
OBBP: '',
OBSP: '',
CurrTime: 0,
rules: {}
};
}
function function4() {
status = false;
myhttp.get('https://example.com/PB.jsp?Exchange=',
function (_html) {
if (_html && _html.length > 10) {
news.pn = {};
$ = cheerio.load(_html);
$('tr[id^="TR"]').each(function () {
status = true;
var symbol = $('td:nth-child(3)', this).text().trim();
var objob = {
'NQ': parseInt($('td:nth-child(11)', this).text().trim()),
};
var post = {
'symbol': symbol,
'nq': objob.NQ
};
connection.query('INSERT INTO NP SET ?', post, function (err,result){
if (err)
{console.log("NP sql insert error : " +symbol);}
else {
console.log("data inserted into NP Table : " +symbol);
}
});
var objstock = news.all[symbol];
if (typeof objstock!='undefined') {
objstock.NQ = objob.NQ;
news.pn[symbol] = objob;
news.all[symbol] = objstock;
if (status) {
io.emit('news', news);
}
}
else
{
console.log('symbol not found');
}
});
if (timerP) {
clearTimeout(timerP);
}
console.log('setTimer function4:' + config.DelayExtractPn);
timerP = setTimeout(function4, config.DelayExtractPn);
}
connection.query('UPDATE MASTER1 SET tbq = (SELECT sum(a.bq) FROM (select distinct symbol, bq from NP) as a)', function (err,result){
if (err)
{console.log("CQ06 skipped: ");}
else {
console.log("Step 6 - Master1 tbq data updated");
}
});
connection.query('UPDATE MASTER1 SET tsq = (SELECT sum(a.sq) FROM (select distinct symbol, sq from NP) as a)', function (err,result){
if (err)
{console.log("CQ07 skipped: ");}
else {
console.log("Step 7 - Master1 tsq data updated");
}
});
});
}
function function5() {
status = false;
myhttp.get('https://example.com/OB.jsp?Exchange=&OrderType=All',
function (_html) {
if (_html && _html.length > 10) {
$ = cheerio.load(_html);
console.log('OB - Step 2 - html loaded for parsing');
news.ob = [];
$('tr[id^="TR"]').each(function () {
var statusOrder = $('td:nth-child(20)', this).text().trim();
if (statusOrder.toLowerCase().indexOf('open') >= 0) {
status = true;
var objob = {
'symbol': $('td:nth-child(6)', this).text().trim(),
'buysell': $('td:nth-child(9)', this).text().trim(),
'ordernumber': $('input[name="Select"]', this).attr('value'),
};
var objstock = news.all[objob.symbol];
objstock.OBBP = objob.buysell == "BUY"?objob.ordernumber:"";
objstock.OBSP = objob.buysell == "SELL"?objob.ordernumber:"";
news.ob.push(objob);
}
});
if (status) {
io.emit('news', news);
}
if (timerOB) {
clearTimeout(timerOB);
}
timerOB = setTimeout(function5, config.DelayExtractOB);
}
});
}
function function6() {
myhttp.get(
'https://example.com/MW.jsp?',
function (_html) {
if (_html && _html.length > 10) {
var $ = cheerio.load(_html);
status = false;
news.mw = [];
var countCheckRule = 0;
var countCheckedRule = 0;
var tmpall = {};
$('tr[onclick]').each(function () {
status = true;
var data1 = $("input[onclick*='Apply(']", this).attr('onclick');
var arrdata1 = data1.split("','");
var stockid = arrdata1[1].split('|')[0];
var symbol = $('td:nth-child(3)', this).text().trim();
var price = parseFloat($('td:nth-child(4)', this).text().trim());
var cTime = stringHelper.getIndiaTime();
var CurrTime = cTime.toLocaleTimeString();//(will be updated every 60 seconds)
news.mw.push({
'symbol': symbol,
'price': price,
'stockid': stockid,
'CurrTime': CurrTime,
});
var objstock = news.all[symbol];
if (!objstock) {
objstock = function3();
}
if (!news.pn[symbol]) {
objstock.NQ = 0;
}
var notfoundob = true;
for (var symbolkey in news.ob) {
if (news.ob[symbolkey].symbol == symbol) {
notfoundob = false;
}
}
if (notfoundob) {
objstock.OBBP = "";
objstock.OBSP = "";
}
objstock.TS = symbol;//trade symbol
objstock.MWP = stockid;//trade id
objstock.LTP = price;
objstock.CurrTime = CurrTime;
rules.checRules(objstock, myhttp, function (rules_res) {
objstock.rules = rules_res;
tmpall[symbol] = objstock;
});
countCheckRule++;
});
rules.rule12(tmpall, function (_tmpall) {
tmpall = _tmpall;
});
news.all = tmpall;
if (!status) {
login();
console.log('MW - Step 9 - logged out');
} else {
io.emit('news', news);
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
} else {
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
});
}
Now i want to use async to ensure that function6 is run only after function4 & function5 is run.
I have tried to learn about async from various forums and have changed the code as follows:
var async = require('async'); //line added
// change made
async.parallel([
function function4(callback) {
status = false;
myhttp.get('https://example.com/PB.jsp?Exchange=',
function (_html) {
if (_html && _html.length > 10) {
news.pn = {};
$ = cheerio.load(_html);
$('tr[id^="TR"]').each(function () {
status = true;
var symbol = $('td:nth-child(3)', this).text().trim();
var objob = {
'NQ': parseInt($('td:nth-child(11)', this).text().trim()),
};
console.log('Posn - Step 3A - Found position:' + symbol);
var post = {
'symbol': symbol,
'nq': objob.NQ
};
connection.query('INSERT INTO NP SET ?', post, function (err,result){
if (err)
{console.log("NP sql insert error : " +symbol);}
else {
console.log("data inserted into NP Table : " +symbol);
}
});
var objstock = news.all[symbol];
if (typeof objstock!='undefined') {
objstock.NQ = objob.NQ;
news.pn[symbol] = objob;
news.all[symbol] = objstock;
if (status) {
io.emit('news', news);
}
}
else
{
console.log('symbol not found');
}
});
if (timerP) {
clearTimeout(timerP);
}
console.log('setTimer function4:' + config.DelayExtractPn);
timerP = setTimeout(function4, config.DelayExtractPn);
}
connection.query('UPDATE MASTER1 SET tbq = (SELECT sum(a.bq) FROM (select distinct symbol, bq from NP) as a)', function (err,result){
if (err)
{console.log("CQ06 skipped: ");}
else {
console.log("Step 6 - Master1 tbq data updated");
}
});
connection.query('UPDATE MASTER1 SET tsq = (SELECT sum(a.sq) FROM (select distinct symbol, sq from NP) as a)', function (err,result){
if (err)
{console.log("CQ07 skipped: ");}
else {
console.log("Step 7 - Master1 tsq data updated");
}
});
callback(); //line added
});
},
function function5(callback) {
status = false;
myhttp.get('https://example.com/OB.jsp?Exchange=&OrderType=All',
function (_html) {
if (_html && _html.length > 10) {
$ = cheerio.load(_html);
console.log('OB - Step 2 - html loaded for parsing');
news.ob = [];
$('tr[id^="TR"]').each(function () {
var statusOrder = $('td:nth-child(20)', this).text().trim();
if (statusOrder.toLowerCase().indexOf('open') >= 0 || statusOrder.toLowerCase().indexOf('trigger pending') >= 0) {
status = true;
var objob = {
'symbol': $('td:nth-child(6)', this).text().trim(),
'buysell': $('td:nth-child(9)', this).text().trim(),
'ordernumber': $('input[name="Select"]', this).attr('value'),
};
var objstock = news.all[objob.symbol];
objstock.OBBP = objob.buysell == "BUY"?objob.ordernumber:"";
objstock.OBSP = objob.buysell == "SELL"?objob.ordernumber:"";
news.ob.push(objob);
}
});
if (status) {
console.log('OB - Step 5 - pushed to html page');
io.emit('news', news);
}
if (timerOB) {
clearTimeout(timerOB);
}
timerOB = setTimeout(function5, config.DelayExtractOB);
}
callback(); //line added
});
}
],
function function6() {
myhttp.get(
'https://example.com/MW.jsp?',
function (_html) {
if (_html && _html.length > 10) {
var $ = cheerio.load(_html);
status = false;
news.mw = [];
var countCheckRule = 0;
var countCheckedRule = 0;
var tmpall = {};
$('tr[onclick]').each(function () {
status = true;
var data1 = $("input[onclick*='Apply(']", this).attr('onclick');
var arrdata1 = data1.split("','");
var stockid = arrdata1[1].split('|')[0];
var symbol = $('td:nth-child(3)', this).text().trim();
var price = parseFloat($('td:nth-child(4)', this).text().trim());
var cTime = stringHelper.getIndiaTime();
var CurrTime = cTime.toLocaleTimeString();//(will be updated every 60 seconds)
news.mw.push({
'symbol': symbol,
'price': price,
'stockid': stockid,
'CurrTime': CurrTime,
});
var objstock = news.all[symbol];
if (!objstock) {
objstock = function3();
}
if (!news.pn[symbol]) {
objstock.NQ = 0;
}
var notfoundob = true;
for (var symbolkey in news.ob) {
if (news.ob[symbolkey].symbol == symbol) {
notfoundob = false;
}
}
if (notfoundob) {
objstock.OBBP = "";
objstock.OBSP = "";
}
objstock.TS = symbol;//trade symbol
objstock.MWP = stockid;//trade id
objstock.LTP = price;
objstock.CurrTime = CurrTime;
rules.checRules(objstock, myhttp, function (rules_res) {
objstock.rules = rules_res;
tmpall[symbol] = objstock;
});
countCheckRule++;
});
//new check rules
rules.rule12(tmpall, function (_tmpall) {
tmpall = _tmpall;
});
news.all = tmpall;
if (!status) {
login();
} else {
io.emit('news', news);
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
} else {
if (timerMW) {
clearTimeout(timerMW);
}
timerMW = setTimeout(function6, config.DelayExtractMW);
}
});
});
Since my original functions do not have any callback, and since async needs callback, i have tried to code a callback in function4 & function5 - but I guess i have not coded it correctly.
I am getting an error in the line where callback is present that states "TypeError: undefined is not a function".
How do i correct this?
Related Question No. 2 : the current code has a timer function whereby function4, function5 and function6 runs with a preset timer. If async works, how do i define a timer whereby the combined set of function4,5 & 6 works based on a preset timer?
Sorry about the long code -- i am new to nodejs and was handed over this code as such and am trying to get this change made.
Thanks for your guidance.
You can instead make function4 and function5 to return promise and then execute function6 only after both function4's and function5's promise gets resolved.
here is my current code
'use strict';
var _ = require('underscore'),
util = require('util'),
events = require('events'),
net = require('net'),
colors = require('colors');
// Chatango Socket connection handler, for both Rooms and PM
// Available events: onconnect, data, error, timeout, close, write ( Note: exceptions must be handled! )
function Socket(host, port)
{
this._host = host;
this._port = port || 443;
this._socket = new net.Socket();
this._pingTask = false;
this._connected = false;
this._firstCommand = true;
this._writeLock = false;
this._writeBuffer = [];
this._buffer = '';
this.connect();
}
util.inherits(Socket, events.EventEmitter);
Socket.prototype.connect = function()
{
if(this._socket._connecting) return;
var self = this;
if(this._socket.destroyed){
var reconnecting = true;
console.log('[SOCKET] reconnecting to '+this._host+':'+this._port);
}else{
var reconnecting = false;
console.log('[SOCKET] connecting to '+this._host+':'+this._port);
}
this._writeLock = true;
if(this._socket._events.connect){
this._socket.connect(this._port, this._host);
}else{
this._socket.connect(this._port, this._host, function() {
self._connected = true;
self._writeLock = false;
self._pingTask = setInterval(function() {
if(self._connected) {
self.write(['']);
}
}, 30000);
self.emit('onconnect');
});
}
if(reconnecting) return;
this._socket.on('data', function(data) {
var buffer = data.toString('utf8');
if(buffer.substr(-1) !== '\x00')
{
self._buffer += buffer;
}
else
{
if(self._buffer != '')
{
buffer = self._buffer + buffer;
self._buffer = '';
}
var messages = buffer.split('\x00');
_.each(messages, function(message){
message = message.replace(/(\r|\n)/g, '');
if(message !== '')
self.emit('data', message);
});
}
});
this._socket.on('error', function(exception) {
self.emit('error', exception);
});
this._socket.on('timeout', function(exception) {
self.emit('timeout', exception);
});
this._socket.on('close', function() {
self._connected = false;
self._writeBuffer = [];
self._writeLock = false;
self._buffer = '';
self._firstCommand = true;
clearInterval(self._pingTask);
self.emit('close');
});
}
Socket.prototype.disconnect = function(){
this._socket.destroy();
}
Socket.prototype.setWriteLock = function(bool) {
this._writeLock = _.isBoolean(bool) && bool;
}
Socket.prototype.write = function(data) {
if(this._connected)
{
if(this._firstCommand)
{
var terminator = '\x00';
this._firstCommand = false;
}
else
var terminator = '\r\n\x00';
if(this._writeLock)
this._writeBuffer.push(data);
else
{
_.each(this._writeBuffer, function(value){
this.write(value);
}.bind(this));
if(data)
this.emit('write', data.join(':'));
this._socket.write(data.join(':') + terminator);
}
}
}
exports.Instance = Socket;
as you can see i am using the net module
i want to change to the ws module and do this using websockets https://github.com/einaros/ws
i've read all kinds of examples but none of them give me what i want
the lib im using is
https://github.com/MakuraYami/derplib
I am trying to include a module i found that will help manage users:
http://www.codeproject.com/Articles/382561/Session-Management-in-Nodejs
Ive copied the code and put it in the same directory as my server.js
I require it by doing:
var express = require('express');
var http = require('http'),
mysql = require("mysql");
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var sessionMgm = require("./sessionManagement");
Now in my socket i do this:
io.sockets.on('connection', function (socket) {
socket.on('setUserInfo', function (data) {
var sess = new Object();
sess.sessionId = socket.id;
sess.userId = data.userId;
sess.username = data.username;
sess.role = data.role;
sessionMgm.add(sess);
});
socket.on("private", function(data) {
if(data.agentName.length <= 0) {
data.agentName = 'Besökare';
}
io.sockets.in('Room_' + data.user_id).emit('updatechat', data.agentName, data.msg);
var user = sessionMgm.getSessionByUserId(data.id);
console.log('::: A socket with ID ' + user + ' connected! ::: ');
});
});
However i keep getting this error:
TypeError: Object # has no method 'getSessionByUserId'
Cant seem to figure out whats wrong, any ideas?
sessionManagement.js:
module.exports = sessionManagement;
var sessions = [];
//User roles list
var userRoles = {
Admin: "administrator",
User: "user",
Supervisor: "supervisor"
};
var sessionManagement = {
indexOf: function(sessionId) {
for(var i in sessions) {
if(sessions[i].sessionId == sessionId)
return i;
}
return null;
},
indexOfUser: function(userId) {
for(var i in sessions) {
if(sessions[i].userId == userId)
return i;
}
return null;
},
add: function(sessionData) {
sessions.push(sessionData);
},
remove: function(sessionId) {
var index = this.indexOf(sessionId);
if(index != null) {
sessions.splice(index, 1);
} else {
return null;
}
},
removeByUserId: function(userId) {
var index = this.indexOf(userId);
if(index != null) {
sessions.splice(index, 1);
} else {
return null;
}
},
getSessionById: function(userId) {
var index = this.indexOfUser(userId);
if(index != null) {
return sessions[index];
} else {
return null;
}
},
getSessionByUserId: function(sessionId) {
var index = this.indexOfUser(userId);
if(index != null) {
return sessions[index];
} else {
return null;
}
},
isAdmin: function(userId) {
var index = this.indexOfUser(userId);
if(index != null) {
if(users[index].role == userRoles.Admin) {
return true;
} else {
return false;
}
} else {
return null;
}
},
getUsersByRole: function(role) {
var usersByRole = [];
for(var i in users) {
if(users[i].role == role)
usersByRole.push(users[i]);
}
return usersByRole;
}
};
As madflow mentioned, you were missing module.exports = sessionManagement in sessionManagement.js
Then you got the error, because you were exporting sessionManagement, before initializing it. Moving the export line to the end of sessionManagement.js should fix that.
module.exports = sessionManagement; // <- you export here
...
...
...
var sessionManagement = { // and initialize here
Although sessionManagement declaration gets hoisted to the top of the module (and that's why you don't get Unexpected identifier or ReferenceError when assigning it to module.exports), it's initialization does not, so what really happens behind the scenes is something like that:
var sessionManagement; // undefined at this point
module.exports = sessionManagement; // <- you export here,
// but sessionManagement is undefined at this point
// and so will be module.exports after this line
...
...
...
sessionManagement = { // and initialize here