Signalr 2.0.0 doesn't behave as previous version - asp.net-web-api

I have updated my server solution to work with MVC 5 and latest version of signalr and have two major issues:
I have overriden the OnConnected function and it is not being invoked.
Messages to client are not being received , calls from the client are being received
this is the client code
define(['jquery', 'toastr', 'Q'], function($, toastr, Q) {
var incidentHubProxy;
var deferred = Q.defer();
var connect = function() {
var connection = $.hubConnection(localStorage.url);
$.connection.hub.logging = true;
incidentHubProxy = connection.createHubProxy('notification');
connection.start()
.done(function () {
toastr.success('Now connected, connection ID=' + connection.id);
setInterval(function () {
incidentHubProxy.invoke('ping');
}, 3000);
deferred.resolve();
})
.fail(function () { toastr.error('Could not connect'); });
incidentHubProxy.on('notify', function (data) {
toastr.info(data.topic);
toastr.info(data.data);
});
incidentHubProxy.on('pong', function (data) {
toastr.info('got pong');
});
return deferred.promise;
};
var joinGroup = function (groupName) {
incidentHubProxy.invoke('joinGroup', groupName);
};
return {
connect: connect,
joinGroup: joinGroup
};
});
i have updated the code to that and still dont work
define(['jquery', 'toastr', 'Q'], function($, toastr, Q) {
var incidentHubProxy;
var deferred = Q.defer();
var connect = function() {
var connection = $.hubConnection(localStorage.url);
$.connection.hub.logging = true;
incidentHubProxy = connection.createHubProxy('notification');
incidentHubProxy.notify = function(data) {
toastr.info(data.topic);
toastr.info(data.data);
};
incidentHubProxy.pong = function(data) {
toastr.info('got pong');
};
connection.start()
.done(function () {
toastr.success('Now connected, connection ID=' + connection.id);
setInterval(function () {
incidentHubProxy.invoke('ping');
}, 3000);
deferred.resolve();
})
.fail(function () { toastr.error('Could not connect'); });
return deferred.promise;
};
var joinGroup = function (groupName) {
incidentHubProxy.invoke('joinGroup', groupName);
};
return {
connect: connect,
joinGroup: joinGroup
};
});

Related

Nodejs - xmlhttprequest promise never finish

module.js
var Promise = require('bluebird');
var XMLHttpRequest = require('xhr2');
function fetchdata(id) {
var url = 'http://www.youtube.com/watch?v=' + id;
return new Promise(function (fulfill, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
var jsonStr;
try {
fulfill(xhr.response);
} catch (e) {
reject(jsonStr);
}
};
xhr.onerror = function(e) {
reject(e);
};
xhr.send('');
});
}
module.exports = {
getdata: function (videoID) {
return new Promise(function (fulfill, reject) {
if (!videoID) {
reject(new Error('Unable to get video id.'));
return;
}
fetchdata(videoID).then(
function (d) {
console.log( d);
}
);
});
}
};
index.js
var parser = require('./module.js');
parser.getdata("ZI4tRn4dOGg", function (data) {
console.log(data);
}
)
I tried to get youtube view page source code with xmlhttprequest.
BUT above code does not finish. I guess it is waiting for something.
Is problem from bluebird? or xhr2? and why does this code never finish?
Your xhr instance had a memory leak, might be a problem with the library, last publish was a year ago. Bluebird was ok. You can fix the hangup by using node-fetch and dropping in this replacement for fetchdata
const fetch = require('node-fetch')
function fetchdata(id) {
var url = 'http://www.youtube.com/watch?v=' + id;
return fetch(url).then(res => res.text())
}

WebSocket connection from node module to chrome extension closing automatically in Windows 10

I use https://www.npmjs.com/package/ws npm package to communicate between my npm module and my chrome extension.
Connection is getting opened, but closes in few seconds.
I researched the topic and I found that I should send messages back and forth between webSocket server and Client to keep it alive.
I am sanding this messages every 2 sec but my connection is still closing.
Interesting stuff is that close event fires on node module side only, while chrome plugin does not fire the event. Here is a code from my chrome extension:
function myPlugin() {
myPlugin.prototype.socket = false;
myPlugin.prototype.isConnected = false;
myPlugin.prototype.port = false;
myPlugin.prototype.pluginName = "Tab Reloader";
myPlugin.prototype.init();
};
myPlugin.prototype = {
initListeners: function () {
chrome.browserAction.onClicked.addListener(function(tab) {
if (!this.isConnected) {
this.connectToServer();
} else {
this.disconnectFromServer();
}
}.bind(this));
},
setPort: function () {
chrome.storage.sync.get(['port'], function(items) {
this.port = items.port || '8001';
}.bind(this));
},
getTabsToReload: function (callback) {
var tabsToReload = [];
chrome.storage.sync.get(['hostName'], function(items) {
if (!items.hostName) {
chrome.tabs.query({active: true}, function(tabs) {
tabs.forEach(function (tab) {
tabsToReload.push(tab);
});
callback(tabsToReload);
});
} else {
chrome.tabs.query({}, function(tabs) {
tabs.forEach(function (tab) {
if (tab.url.indexOf(items.hostName) != -1) {
tabsToReload.push(tab);
}
});
callback(tabsToReload);
});
}
}.bind(this));
},
initSocketListeners: function () {
var fileExtIndex,
fileExt,
file;
this.socket.onmessage = function (ev) {
file = ev.data.toString();
fileExtIndex = file.lastIndexOf('.') + 1;
fileExt = file.slice(fileExtIndex),
fileNameStandardize = file.replace(/\\/g, '\/'),
indexOfLastSeparator = fileNameStandardize.lastIndexOf('/') + 1,
fileName = file.slice(indexOfLastSeparator);
if (file != 'pong' && file.indexOf('connected to server!!!') == -1) {
//do stuff
} else {
if (file == 'pong') {
this.isAlive = true;
}
}
}.bind(this);
this.socket.addEventListener('close', function (ev) {
console.log('connection Closed')
clearInterval(this.aliveInterval);
chrome.browserAction.setIcon({
path: {
"16": "img/icon_disabled_16.png",
"24": "img/icon_disabled_24.png",
"32": "img/icon_disabled_32.png"
}
});
this.isConnected = false;
}.bind(this));
},
connectToServer: function () {
this.socket = new WebSocket("ws://localhost:" + this.port);
this.socket.addEventListener('error', function (ev) {
this.isConnected = false;
alert('Error connecting to websocket server, make sure it\'s running and port ' + this.port + ' is not occupied by other process');
}.bind(this));
this.socket.addEventListener('open', function (ev) {
this.isConnected = true;
this.socket.send(this.pluginName + ' connected to server!!!');
this.initSocketListeners();
this.stayConnected();
this.isAlive = true;
this.aliveInterval = setInterval(function () {
this.checkIfAlive();
}.bind(this), 2500);
this.getTabsToReload(function (tabsToReload) {
tabsToReload.forEach(function (tab) {
chrome.tabs.update(tab.id, {url: tab.url});
});
});
chrome.browserAction.setIcon({
path: {
"16": "img/icon_active_16.png",
"24": "img/icon_active_24.png",
"32": "img/icon_active_32.png"
}
});
}.bind(this));
},
disconnectFromServer: function () {
this.socket.close();
},
stayConnected: function () {
setTimeout(function () {
this.socket.send('ping');
if (this.isConnected) {
this.stayConnected();
}
}.bind(this), 1000);
},
checkIfAlive: function () {
this.isAlive = false;
setTimeout(function () {
console.log(this.isAlive)
if (!this.isAlive) {
console.log(this.isAlive)
this.disconnectFromServer();
}
}.bind(this), 2000);
},
init: function () {
this.setPort();
this.initListeners();
}
}
window.onload = new myPlugin();
And here is my node module code:
"use strict";
//var WebSocketServer = require('websocketserver');
//var WebSocketServer = require("nodejs-websocket")
var WebSocket = require('ws');
class MyModule {
constructor(options) {
this.options = options;
this.server = false;
this.pluginName = 'Some';
this.isConnected = false;
this.connection = false;
this.init();
return this.refreshTab.bind(this);
}
init() {
var port = this.options ? this.options.port : false;
this.server = new WebSocket.Server({port: port || 8001});
this.server.on('connection', (websocket) => {
console.log('Connection open');
this.websocket = websocket;
this.isConnected= true;
this.initListeners();
});
}
refreshTab(uploadedFiles) {
if (this.isConnected) {
if (Array.isArray(uploadedFiles)) {
uploadedFiles.forEach(function (el) {
this.websocket.send(el.toString());
}.bind(this));
} else {
this.websocket.send(uploadedFiles ? uploadedFiles.toString() : 'reload');
}
} else {
console.log('You are not connected to server yet.');
}
}
initListeners() {
this.websocket.on('message', (message) => {
if (message == 'ping') {
this.websocket.send('pong');
}
});
this.websocket.on('close', () => {
this.isConnected = false;
console.log(this.pluginName + ' connection is closed');
});
}
};
module.exports = MyModule;
Appreciate any help,
Thanks in advance.
So my problem was actually in manifest.json
"background": {
"scripts": ["js/tab_reloader.js"],
"persistent": false
}
"persistent" was set to false, it transformed my Background page into Event Page. And event page is unloaded from memory after a period of time, which was killing the connection. After I set "persistent" to true the problem got fixed.

node.js - Socket IO times out after some time

I'm trying to build up a socket.io server for my own multiplayer game, but for some reason the server goes down after a certain amount of time and I don't know why. I have tried several ways to run the server (nodemon and forever, everything with or without screen). I don't think that this is an inactivity problem because I added a random stuff generator to simulate some activity on the server, yet the problem persists. My cpu load with the running server stays between 2-3 %. I'm running node 4.x and the current stable socket.io build (1.3.6).
And here is my code:
var shortId = require('shortid'),
io = require('socket.io')(process.env.PORT || 4567),
mysql = require('mysql'),
connection = mysql.createConnection({
host: 'localhost',
user: 'xxx',
password: 'xxx',
database: 'xxx'
});
var clients = [];
var clientLookup = {};
//Placed Components (builded stuff from players or enviroment)
var placed_components = 'Server1_PlacedC';
connection.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
});
setInterval(function () {
var random = Math.random();
//connection.query(
// 'INSERT INTO '+placed_components+' SET ?',
// {data:countdown},
// function(err,result){
// if (err) throw err;
// }
//);
console.log(random);
}, 100);
io.on('connection', function (socket) {
var currentClient;
console.log('connected', socket.id);
//////////////////////////////////////////////////////////////////////////////
socket.on('disconnect', function () {
console.log('player disconnected', currentClient.id);
socket.broadcast.emit('disconnected', currentClient)
var index = clientLookup[currentClient.id];
clients.splice(index, 1);
})
///////////////////////////////////////////////////////////////////////////// /
socket.on('register', function (data) {
currentClient = {
id: shortId.generate(),
health: 100,
isDead: false
};
console.log('registering', currentClient.id);
clients.push(currentClient);
clientLookup[currentClient.id] = currentClient;
socket.emit('registerSuccess', {id: currentClient.id});
socket.broadcast.emit('spawn', {id: currentClient.id});
console.log('connected players', clients.length);
clients.forEach(function (client) {
if (currentClient.id == client.id)
return;
socket.emit('spawn', {id: client.id});
console.log('sending spawn to new player for playerid', client.id);
})
});
socket.on('beep', function () { // Beep Request
socket.emit('boop');
console.log("received some beep!");
});
socket.on('move', function (data) {
data.id = currentClient.id;
socket.broadcast.emit('move', data);
//console.log(JSON.stringify(data));
});
socket.on('ShareObject', function (data) {
data.id = currentClient.id;
socket.broadcast.emit('ReveiveObject', data);
console.log(JSON.stringify(data));
});
socket.on('SharePlayerAnimation', function (data) {
data.id = currentClient.id;
socket.broadcast.emit('BroadcastPlayerAnimation', data);
console.log("a Player changed his animation" + JSON.stringify(data));
});
//////////////////////////////////////////////////////////////////////////////
socket.on('benchmark', function (data) {
console.log(data);
});
//////////////////////////////////////////////////////////////////////////////
})
console.log('server started');

How to make wrapped jQuery promise fire the reject callback on error?

I'm wrapping a simple jQuery promise with RSVP and noticed that when I cause an error on purpose the failure callback is never invoked. I assume it's because when you use vanilla jQuery and the callback throws an error, the returned promise will not be moved to failed state (the opposite of the spec).
If I need to use jQuery $.ajax but I want to get true resolve/reject callbacks with RSVP what (if anything) can I do to the example below?
var peoplePromise = new Ember.RSVP.Promise(function(resolve, reject) {
$.getJSON('/api/people/', resolve).fail(reject).error(reject);
});
var catPromise = new Ember.RSVP.Promise(function(resolve, reject) {
$.getJSON('/api/cats/', resolve).fail(reject).error(reject);
});
Ember.RSVP.all([peoplePromise, catPromise]).then(function(things) {
things[0].forEach(function(hash) {
var thing = App.Person.create(hash);
Ember.run(self.people, self.people.pushObject, thing);
});
things[1].forEach(function(hash) {
var wat = hash.toJSON(); //this blows up
var thing = App.Person.create(hash);
Ember.run(self.people, self.people.pushObject, thing);
});
}, function(value) {
alert(value.status + ": promise failed " + value.responseText);
});
Example here: http://www.youtube.com/watch?feature=player_detailpage&v=g5CSaK3HqVA#t=1080
var ajaxPromise = function(url, options){
return Ember.RSVP.Promise(function(resolve, reject) {
var options = options || {};
options.success = function(data){
resolve(data);
};
options.error = function(jqXHR, status, error){
reject([jqXHR, status, error]);
};
$.ajax(url, options);
});
};
var peoplePromise = ajaxPromise('/api/people/',{
dataType: "json"
});
var catPromise = ajaxPromise('/api/cats/',{
dataType: "json"
});
Ember.RSVP.all([peoplePromise, catPromise]).then(function(things) {
things[0].forEach(function(hash) {
var thing = App.Person.create(hash);
Ember.run(self.people, self.people.pushObject, thing);
});
things[1].forEach(function(hash) {
var wat = hash.toJSON(); //this blows up
var thing = App.Person.create(hash);
Ember.run(self.people, self.people.pushObject, thing);
});
}, function(args) {
var jqXHR = args[0];
alert(jqXHR.status + ": promise failed " + jqXHR.responseText);
});
http://emberjs.jsbin.com/aREDaJa/1/

AngularJS - Strange behaviour of promises in connection with notify()

As I want to implement a chat in AngularJS, I want to use the promise/deferred principle. My ChatService looks like the following:
factory('ChatService', ['$q', '$resource', function($q, $resource) {
var Service = {};
var connected = false;
var connection;
var chatResource = $resource('/guitars/chat/:action', {action: '#action'}, {
requestChatroomId: {
params: {
action: 'requestChatroomId'
},
method: 'GET'
},
sendMessage: {
params: {
action: 'sendMessage'
},
method: 'POST'
}
});
Service.connect = function(cb) {
var deferred = $q.defer();
chatResource.requestChatroomId(function(data) {
connection = new WebSocket('ws://127.0.0.1:8888/realtime/' + data.chatroomId);
connection.onerror = function (error) {
deferred.reject('Error: ' + error);
};
connection.onmessage = function (e) {
cb.call(this, e.data);
deferred.notify(e.data);
};
connected = true;
});
return deferred.promise;
};
Service.sendMessage = function(msg) {
if(!connected) {
return;
}
chatResource.sendMessage({message: msg});
}
return Service;
}])
My controller using the ChatService is:
app.controller('ChatCtrl', ['$scope', 'ChatService', function($scope, ChatService) {
$scope.chat = {};
$scope.chat.conversation = [];
var $messages = ChatService.connect(function(message) {
$scope.$apply(function() {
// #1 THIS FIRES EVERY TIME
$scope.chat.conversation.push(message);
});
});
$messages.then(function(message) {
console.log('Finishes - should never occur!')
}, function(error) {
console.log('An error occurred!')
}, function(message) {
// #2 THIS FIRES ONLY IF THERE IS AN INTERACTION WITH THE ANGULAR MODEL
console.log(message);
});
$scope.sendMessage = function(event) {
ChatService.sendMessage($scope.chat.message);
$scope.chat.message = '';
};
}]);
If something is pushed from the server, callback #1 is called, but callback #2 wont be called until there is some interaction with the angular-model, i.e. start writing something in the input-Box. What is the reason for that behaviour?
Okay the reason was, that AngularJS was not aware of a change. So I injected the $rootScope to my ChatService:
factory('ChatService', ['$q', '$resource', '$rootScope', function($q, $resource, $rootScope) {
and in connection.onmessage I called $apply() on $rootScope:
connection.onmessage = function (e) {
deferred.notify(e.data);
$rootScope.$apply();
};

Resources