I'm developing a realtime socket.io app using AngularJS, Nodejs, and Socket.io both the server and client side libraries. I'm using the module called angular-socket-io however when I tell Angular to connect, the more I refresh the page it seems like multiple connections keep being maintained with Socket.IO and I'm the only user on the page right now.
In my server logs I keep seeing many socket IDs print out and when I refresh the application page, it takes a while for it to reconnect. Watching the console I see it communicating with the server a lot (probably has to do with the multiple socket connection handshakes) but after a good minute or two, it finally stabilizes and starts receiving data again.
I think I'm doing this wrong, or is this normal? Does anyone have any good advice for using Socket.IO in angular so that when the page refreshes it reconnects once and gets rid of all previous connections so that only one is maintained at all times?
Here's some code samples. Just to clarify, the btford.socket-io prefixes all forwarded socket events with "socket:". So in my example it would be "socket:start".
myApp.js
angular.module('myApp', [ 'btford.socket-io', 'myControllers' ])
.config([ 'socketProvider', function(socketProvider) {
var appSocket = io.connect('http://live.myapp.com');
socketProvider.ioSocket(appSocket);
}])
.run(['socket', function(socket) {
socket.forward('error');
socket.forward('start'); // this is the event i'm trying to listen for
});
myController
angular.module('myControllers').controller('startController', [
'$scope',
function($scope) {
$scope.$on('socket:start', function(ev, data) {
$scope.activeDrivers.push({
name: data.user.firstName + " " + data.user.lastName
});
$scope.driversActiveTab.count = $scope.activeDrivers.length;
});
}
]);
So that's it, and I can't figure out why it keeps making so many connections to the server! Thanks for the help in advance!
you should generate a id(ex:random string) in your angular page.when you connect server first.record this id in your server, id is bind your socket. when client disconnect,will call server 'disconnect' event,listen this event and clean the socket.
Answering my own question. Per this page, if you have nodejs instances running across servers or on multiple cores you must use the RedisStore to queue and properly handle socket requests. The strange behavior I described in my question was the browser attempting to connect to one of my 4 cores and missing responses from other cores. I followed the instructions to enable Redis as the data store for SocketIO and all of the problems went away.