SignalR connection closed but still works after angularjs scope destroy - asp.net

I have a SignalR hub proxy in angularjs factory like this.
var app = angular.module('app');
app.factory("signalRHubProxy", ['$rootScope', "$timeout", function ($rootScope, $timeout) {
function signalRHubProxyFactory(serverUrl, hubName) {
var connection = $.hubConnection(serverUrl);
var proxy = connection.createHubProxy(hubName);
connection.disconnected(function () {
$timeout(function () {
connection.start();
}, 5000)
});
return {
on: function (eventName, callback) {
proxy.on(eventName, function (result) {
$rootScope.$apply(function () {
if (callback) {
callback(result);
}
});
});
connection.start();
},
stop: function () {
connection.stop();
},
connection: connection
};
}
return signalRHubProxyFactory;
}]);
I used connection timeout because sometimes server does not listen, so I can retry.
I am using this factory in my controller:
app.controller("directiveController", function($scope, signalRHubProxy){
var signalRProxy = signalRHubProxy(
"url",
"hubname");
signalRHubProxy.on("datapush", function(data){
});
$scope.$destroy(function(){
signalRHubProxy.stop();
??? how to kill signalr hub
})
})
But when I remove my directive, signalR still works.

I believe when you call stop(), it calls disconnected event, which will just start the connection again. You might need to check if the disconnection was intentional (with a simple boolean variable), then just avoid restarting the connection:
app.factory("signalRHubProxy", ['$rootScope', "$timeout", function ($rootScope, $timeout) {
function signalRHubProxyFactory(serverUrl, hubName) {
var connection = $.hubConnection(serverUrl);
var proxy = connection.createHubProxy(hubName);
var manualStop = false;
connection.connected(function () {
manualStop = false; // reset variable if connected
});
connection.disconnected(function () {
if (manualStop)
return;
$timeout(function () {
connection.start();
}, 5000)
});
return {
on: function (eventName, callback) {
proxy.on(eventName, function (result) {
$rootScope.$apply(function () {
if (callback) {
callback(result);
}
});
});
connection.start();
},
stop: function () {
manualStop = true;
connection.stop();
},
connection: connection
};
}
return signalRHubProxyFactory;
}]);
Also, make sure $scope.$destroy is being called.
Some people recommend calling $.connection.hub.stop(); instead of connection.stop();, although I don't really know whether it has some significant difference.

Related

AWS Lambda Nodejs async.waterfall not executing MQTT Function

I am trying to use async.waterfall in the exports handler, and call functions sequentially. One of the function is related to MQTT message publishing. While the functions are being called, but when the MQTT function gets called, it just stops and not calls the require ('MQTT').
exports.handler = function(event, context) {
var async = require('async');
async.waterfall([
function(callback) {
retrieveEmailId(apiAccessToken,callback)
},
function(emailId, callback) {
retrieveDeviceDetails(callback)
},
function(deviceDetail, callback) {
publishMsg(callback)
}
], function(err, result) {
if (err) console.log('Error :: \n' + err);
});
}
function retrieveEmailId(accessToken, callback) {
var getEmailFromAlexaProfileObj = require('./GetEmailFromAlexaProfile');
getEmailFromAlexaProfileObj.doIt(accessToken, function(returnVal) {
console.log(returnVal);
callback(null, returnVal)
});
}
function retrieveDeviceDetails(callback) {
var getDevcieDetailsObj = require('./GetDevcieDetails');
getDeviceDetailsObj.doIt(null, function(returnVal) {
console.log(returnVal);
callback(null, returnVal)
});
}
function publishMsg() {
var mqtt = require('mqtt');
var options = {
clientId: "xxx",
username: "yyy",
password: "zzz",
clean: true
};
var client = mqtt.connect("mqtt://xxx.com", options)
client.on("connect", function () {
client.publish('xxx/yyy/L1', "1", options);
client.end();
});
}
Have you tried running the code locally using "lambda-local"? Does that sequence of call work along with the last one that is MQTT? What have you noticed when you invoke "require('mqtt')" within lambda?
Problem got resolved if the require variable is done prior to exports.handler.
for example....
var AWS = require('aws-sdk');
var async = require('async');
exports.handler = function(event, context) {
....
}

Best Practices for reconnecting a disconnected SignalR client (JS)

I'd like to improve the resilience of my clientside implementation of a signalR client.
Currently, I do this:
hub.server.sendClientNotification(string, appSettings.username());
However occasionally, an exception related to connectivity is thrown because either the server is not responding or the client's internet connection has become unusable.
I'd like to solve this by queuing up requests and then doing something like this:
try {
// pop from queue
hub.server.sendClientNotification(string, appSettings.username());
// success - discard element
} catch (e) {
// requeue element
}
With this kind of implementation, would I need to re-initialize my signalR connection using $.connection.hub.start between disconnects, or can I just continue attempting hub transmits within an interval?
This is what I'm proposing:
var hub = null;
const internalQueue = [];
const states = {
connecting: 0, connected: 1, reconnecting: 2, disconnected: 4
}
const signalrModule = {};
var isInitialized = false;
const connectSignalR = function () {
return new Promise(function (resolve, reject) {
if ($.connection.hub.state == states.connected) {
resolve();
} else {
window.hubReady = $.connection.hub.start({ transport: ["serverSentEvents", "foreverFrame", "longPolling"] });
window.hubReady.done(function () {
isInitialized = true;
resolve();
});
window.onbeforeunload = function (e) {
$.connection.hub.stop();
};
}
})
}
signalrModule.init = function (handleNotification) {
hub = $.connection.appHub;
hub.client.clientNotification = handleNotification;
$.connection.hub.qs = {
"username": appSettings.username()
};
connectSignalR();
}
const tryEmptyQueue = function () {
connectSignalR().then(function() {
if (isInitialized) {
var continueTrying = true;
while (internalQueue.length && continueTrying) {
const nextMessage = internalQueue.shift();
try {
hub.server.sendClientNotification(nextMessage, appSettings.username());
} catch (e) {
internalQueue.push(nextMessage);
continueTrying = false;
}
}
}
})
}
signalrModule.sendClientNotification = function (message) {
if (typeof message != "string") {
message = JSON.stringify(message);
}
if (isInitialized) {
try {
hub.server.sendClientNotification(message, appSettings.username());
tryEmptyQueue();
} catch (e) {
logger.log("SignalR disconnected; queuing request", logger.logLevels.warning);
internalQueue.push(message);
}
} else {
internalQueue.push(message);
};
}
const internalQueueInterval = setInterval(function () {
tryEmptyQueue();
}, 5000);
return signalrModule;
Follow the documentation
In some applications you might want to automatically re-establish a connection after it has been lost and the attempt to reconnect has timed out. To do that, you can call the Start method from your Closed event handler (disconnected event handler on JavaScript clients). You might want to wait a period of time before calling Start in order to avoid doing this too frequently when the server or the physical connection are unavailable. The following code sample is for a JavaScript client using the generated proxy.
$.connection.hub.disconnected(function() {
setTimeout(function() {
$.connection.hub.start();
}, 5000); // Restart connection after 5 seconds.
});

Angular client with signalR service not fire controller method

I have angular service where i got methods which are called from server when user connect or disconnect from my app
(function () {
//'use strict';
app.service('PrivateChatService', ['$rootScope', '$location', function PrivateChatService($rootScope, $location){
var online_users = [];
var proxy = $.connection.chatHub;
return {
addOnlineUser:
proxy.client.newOnlineUser = function (user) {
var newUser = ({
connectionId: user.ConnectionId,
UserName: user.UserName
});
online_users.push(newUser);
$.connection.hub.start()
},
removeOfflineUser: proxy.client.onUserDisconnected = function (id, user) {
var index = 0;
//find out index of user
angular.forEach(online_users, function (value, key) {
if (value.connectionId == id) {
index = key;
}
})
online_users.splice(index, 1);
$.connection.hub.start()
},
}
}])})();
Here i got controller method which i want to be fired when server calls newOnlineUser
PrivateChatService.newOnlineUser(function (user) {
$scope.online_users.push(newUser);
console.log("newOnlineUser finished");
});
So my question is. Is it possible to make with generated proxy or i have to use non-generated proxy access to those methods with which i am not very familiar.
With generated proxy as i show above it never reach my controller method to update my data in controller scope
Since nobody responded, what i find somehow odd. I found out this is working. I am not sure if this is good aproach since nobody answered and i didnt find any information how should this be solved.
app.service('PrivateChatService', ['$rootScope', '$location', function PrivateChatService($rootScope, $location){
var online_users = [];
var connection = $.hubConnection();
var proxy = connection.createHubProxy('chatHub');
function signalrCall(eventName, callback) {
proxy.on(eventName, function (user) {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(proxy, args)
})
});
connection.start();
}
return {
addOnlineUser: function (eventName, callback) {
signalrCall(eventName, callback);
},
getActiveUsers: function (eventName, callback) {
signalrCall(eventName, callback);
},
removeOfflineUser: function (eventName, callback) {
signalrCall(eventName, callback);
}
}
}])
angular controller methods
PrivateChatService.addOnlineUser("newOnlineUser", function (user) {
var newUser = ({
connectionId: user.ConnectionId,
UserName: user.UserName
});
$scope.online_users.push(newUser);
console.log("newOnlineUser finished");
});
PrivateChatService.getActiveUsers("getOnlineUsers", function (onlineUsers) {
angular.forEach($scope.online_users, function (scopeValue, scopeKey) {
//loop through received list of online users from server
angular.forEach(onlineUsers, function (serverListValue, serverListKey) {
if (!(serverListValue.ConnectionId == scopeValue.connectionId)) {
var newUser = ({
connectionId: serverListValue.ConnectionId,
UserName: serverListValue.UserName
});
$scope.online_users.push(newUser);
}
})
})
console.log("getOnlineUsers finished");
});
PrivateChatService.removeOfflineUser("onUserDisconnected", function (user) {
var index = 0;
//find out index of user
angular.forEach($scope.online_users, function (value, key) {
if (value.connectionId == user) {
index = key;
}
})
$scope.online_users.splice(index, 1);
});

Meteor External API calls works but client gets Undefined

Client Side:
Template.storeInfo.events({
'click #btn-user-data': function(e) {
Meteor.call('callApi', function(err, data) {
$('#result').text(JSON.stringify(data, undefined, 4));
console.log(data); //Not working!!
});
}
});
Server Side:
storeApi.prototype.retrieve = function(endpoint) {
try {
var gotiye = HTTP.get(endpoint);
console.log(gotiye); //Works!
return gotiye;
} catch (err) {
throw new Error("Failed to fetch call GET retrieve from store. " + err.message);
}
};
storeApi.prototype.getStoreInfo = function() {
var url = this.rootApiUrl.replace(this.endpointToken,
this.endpoints.store);
this.retrieve(url);
};
Meteor.methods({
callApi: function() {
var stnvy = new storeApi(Meteor.user().services.store.accessToken);
var data = stnvy.getStoreInfo();
return data;
}
});
Why it works on server side but impossible to use in client side? Is collection the only way to use this?
Forgot to return it at getStoreInfo function return this.retrieve(url); and it works! :)

How to set a timeout on a http.request() in Node?

I'm trying to set a timeout on an HTTP client that uses http.request with no luck. So far what I did is this:
var options = { ... }
var req = http.request(options, function(res) {
// Usual stuff: on(data), on(end), chunks, etc...
}
/* This does not work TOO MUCH... sometimes the socket is not ready (undefined) expecially on rapid sequences of requests */
req.socket.setTimeout(myTimeout);
req.socket.on('timeout', function() {
req.abort();
});
req.write('something');
req.end();
Any hints?
2019 Update
There are various ways to handle this more elegantly now. Please see some other answers on this thread. Tech moves fast so answers can often become out of date fairly quickly. My answer will still work but it's worth looking at alternatives as well.
2012 Answer
Using your code, the issue is that you haven't waited for a socket to be assigned to the request before attempting to set stuff on the socket object. It's all async so:
var options = { ... }
var req = http.request(options, function(res) {
// Usual stuff: on(data), on(end), chunks, etc...
});
req.on('socket', function (socket) {
socket.setTimeout(myTimeout);
socket.on('timeout', function() {
req.abort();
});
});
req.on('error', function(err) {
if (err.code === "ECONNRESET") {
console.log("Timeout occurs");
//specific error treatment
}
//other error treatment
});
req.write('something');
req.end();
The 'socket' event is fired when the request is assigned a socket object.
Just to clarify the answer above:
Now it is possible to use timeout option and the corresponding request event:
// set the desired timeout in options
const options = {
//...
timeout: 3000,
};
// create a request
const request = http.request(options, response => {
// your callback here
});
// use its "timeout" event to abort the request
request.on('timeout', () => {
request.destroy();
});
See the docs:
At this moment there is a method to do this directly on the request object:
request.setTimeout(timeout, function() {
request.abort();
});
This is a shortcut method that binds to the socket event and then creates the timeout.
Reference: Node.js v0.8.8 Manual & Documentation
The Rob Evans anwser works correctly for me but when I use request.abort(), it occurs to throw a socket hang up error which stays unhandled.
I had to add an error handler for the request object :
var options = { ... }
var req = http.request(options, function(res) {
// Usual stuff: on(data), on(end), chunks, etc...
}
req.on('socket', function (socket) {
socket.setTimeout(myTimeout);
socket.on('timeout', function() {
req.abort();
});
}
req.on('error', function(err) {
if (err.code === "ECONNRESET") {
console.log("Timeout occurs");
//specific error treatment
}
//other error treatment
});
req.write('something');
req.end();
There is simpler method.
Instead of using setTimeout or working with socket directly,
We can use 'timeout' in the 'options' in client uses
Below is code of both server and client, in 3 parts.
Module and options part:
'use strict';
// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js
const assert = require('assert');
const http = require('http');
const options = {
host: '127.0.0.1', // server uses this
port: 3000, // server uses this
method: 'GET', // client uses this
path: '/', // client uses this
timeout: 2000 // client uses this, timesout in 2 seconds if server does not respond in time
};
Server part:
function startServer() {
console.log('startServer');
const server = http.createServer();
server
.listen(options.port, options.host, function () {
console.log('Server listening on http://' + options.host + ':' + options.port);
console.log('');
// server is listening now
// so, let's start the client
startClient();
});
}
Client part:
function startClient() {
console.log('startClient');
const req = http.request(options);
req.on('close', function () {
console.log("got closed!");
});
req.on('timeout', function () {
console.log("timeout! " + (options.timeout / 1000) + " seconds expired");
// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js#L27
req.destroy();
});
req.on('error', function (e) {
// Source: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js#L248
if (req.connection.destroyed) {
console.log("got error, req.destroy() was called!");
return;
}
console.log("got error! ", e);
});
// Finish sending the request
req.end();
}
startServer();
If you put all the above 3 parts in one file, "a.js", and then run:
node a.js
then, output will be:
startServer
Server listening on http://127.0.0.1:3000
startClient
timeout! 2 seconds expired
got closed!
got error, req.destroy() was called!
Hope that helps.
For me - here is a less confusing way of doing the socket.setTimeout
var request=require('https').get(
url
,function(response){
var r='';
response.on('data',function(chunk){
r+=chunk;
});
response.on('end',function(){
console.dir(r); //end up here if everything is good!
});
}).on('error',function(e){
console.dir(e.message); //end up here if the result returns an error
});
request.on('error',function(e){
console.dir(e); //end up here if a timeout
});
request.on('socket',function(socket){
socket.setTimeout(1000,function(){
request.abort(); //causes error event ↑
});
});
Elaborating on the answer #douwe here is where you would put a timeout on a http request.
// TYPICAL REQUEST
var req = https.get(http_options, function (res) {
var data = '';
res.on('data', function (chunk) { data += chunk; });
res.on('end', function () {
if (res.statusCode === 200) { /* do stuff with your data */}
else { /* Do other codes */}
});
});
req.on('error', function (err) { /* More serious connection problems. */ });
// TIMEOUT PART
req.setTimeout(1000, function() {
console.log("Server connection timeout (after 1 second)");
req.abort();
});
this.abort() is also fine.
You should pass the reference to request like below
var options = { ... }
var req = http.request(options, function(res) {
// Usual stuff: on(data), on(end), chunks, etc...
});
req.setTimeout(60000, function(){
this.abort();
});
req.write('something');
req.end();
Request error event will get triggered
req.on("error", function(e){
console.log("Request Error : "+JSON.stringify(e));
});
Curious, what happens if you use straight net.sockets instead? Here's some sample code I put together for testing purposes:
var net = require('net');
function HttpRequest(host, port, path, method) {
return {
headers: [],
port: 80,
path: "/",
method: "GET",
socket: null,
_setDefaultHeaders: function() {
this.headers.push(this.method + " " + this.path + " HTTP/1.1");
this.headers.push("Host: " + this.host);
},
SetHeaders: function(headers) {
for (var i = 0; i < headers.length; i++) {
this.headers.push(headers[i]);
}
},
WriteHeaders: function() {
if(this.socket) {
this.socket.write(this.headers.join("\r\n"));
this.socket.write("\r\n\r\n"); // to signal headers are complete
}
},
MakeRequest: function(data) {
if(data) {
this.socket.write(data);
}
this.socket.end();
},
SetupRequest: function() {
this.host = host;
if(path) {
this.path = path;
}
if(port) {
this.port = port;
}
if(method) {
this.method = method;
}
this._setDefaultHeaders();
this.socket = net.createConnection(this.port, this.host);
}
}
};
var request = HttpRequest("www.somesite.com");
request.SetupRequest();
request.socket.setTimeout(30000, function(){
console.error("Connection timed out.");
});
request.socket.on("data", function(data) {
console.log(data.toString('utf8'));
});
request.WriteHeaders();
request.MakeRequest();

Resources