I am working on an Ionic app with Angular.js. I have 2 page templates in my app, namely login and chat. Each of these have their own states. On the login page, user enters their name and hit login. This makes the state change from login to chat. Here the user can chat with other users using Socket.io events. This works fine.
But in some case, user may want to disconnect/logout and re-login with another name. In such a situation, socket.io does not connect to the server and the application does not respond as soon as the login button is clicked i.e. when the application tried to connect to the server. Here is the code.
My Socket Connection Service
.factory('socket',function(socketFactory){
//Create socket and connect to http://chat.socket.io
var myIoSocket = io.connect('https://node-samarthagarwal.c9.io',
{
'forceNew': true,
'reconnection': false,
'reconnectionDelay': 1000,
'reconnectionDelayMax' : 5000,
'reconnectionAttempts': 5
});
mySocket = socketFactory({
ioSocket: myIoSocket
});
return mySocket;
})
Code on my Login Button
$scope.nickname = nickname;
console.log($scope.nickname);
//sanitize the nickname
if(nickname)
{
$state.go('chat',{nickname: nickname},{reload: true})
}
}
Code of the Controller for Chatting page
.controller('ChatController',function(socket, $scope, $sce, $state, $cordovaMedia, $ionicPopup, $ionicPlatform, $ionicLoading, $stateParams, $ionicScrollDelegate, sharedProperties, $timeout) {
$scope.statusMessage = "Welcome to ChatterBox"
$scope.messages = [];
$scope.nickname = $stateParams.nickname;
$scope.userData = {};
$scope.reLogin = true;
var COLORS = ['#f44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5', '#009688'];
$ionicLoading.show({template: "Connecting..."});
if(sharedProperties.getProperty().isFBAuthenticated) // Meaning that FB Authentication is used
{
var user = sharedProperties.getProperty();
socket.on('connect',function(){
console.log(this.id);
$scope.userData.socketId = this.id;
$scope.userData.fullName = $stateParams.nickname;
$scope.userData.displayPicture = user.displayPicture;
$scope.userData.color = $scope.getUsernameColor($stateParams.nickname);
//alert(JSON.stringify($scope.userData));
socket.emit("onlineUserUpdateAdd", $scope.userData);
.....
......
.......
}
}
I learnt that we cannot create two socket connections. What should I do here, so that I can create another connection or reuse the existing one?
I just added this code to my Controller
if(!socket.connected)
socket.connect();
This reuses an existing connection.