I created a chat app using socket.io, everything works very well except for when one of the users refresh. For instance:
If user A joins room 1, and user B joins room 1, they can communicate smoothly. If user A refreshes his browser, he can still send messages to user B in real time, but user B no longer sends user A messages in real time.
For some reason, when a user refreshes the page, he is no longer able to receive messages in real time. Here is how I have setup my chat system:
server side:
server.listen(port);
var io = require('socket.io').listen(server);
io.on('connection', function(socket){
console.log("User Connected");
socket.on('comment', function(data){
//socket.broadcast.emit('comment', data);
console.log('server sidecomment');
socket.broadcast.to(data.chatId).emit('comment',data);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('join:room', function(data){
socket.join(data.chatId);
socket.broadcast.to(data.chatId).emit('join:room', data)
console.log('joined room: ' + data.chatId);
});
socket.on('leave:room', function(data){
socket.leave(data.chatId);
console.log('left room: ' + data.chatId);
})
socket.on('typing', function(data){
console.log('server side start typing');
console.log(data);
socket.broadcast.to(data.chatId).emit('typing',data);
});
socket.on('stoptyping', function(data){
console.log('server side stop typing');
socket.broadcast.to(data.chatId).emit('stoptyping');
});
});
client side:
$scope.$on("$destroy", function() {
console.log('leaving page');
socket.emit('leave:room', {
'chatId': post.chatId
});
var leaveMessage = auth.currentUser() + ' has left';
posts.addComment(post._id, {
body: leaveMessage,
author: 'server'
}).success(function(comment) {
$scope.post.comments.push(comment);
});
});
socket.on('comment', function(data) {
console.log('client side comment');
$scope.post.comments.push(data);
});
socket.on('join:room', function(data) {
var joinedMessage = {
body: data.author + ' has joined',
author: 'server'
};
$scope.post.comments.push(joinedMessage);
});
$scope.whenTyping = function() {
socket.emit('typing', {
'chatId': post.chatId,
'author': auth.currentUser()
});
}
$scope.notTyping = function() {
socket.emit('stoptyping', {
'chatId': post.chatId
});
}
socket.on('typing', function(data) {
$scope.typing = data.author + ' is typing';
});
socket.on('stoptyping', function() {
$scope.typing = '';
});
My question is: Is the socket being timed out? If it is, is there a way I can prevent it from being timed out?