lundi 30 mars 2015

Socket.io - Override text when user refresh page

I solve this problem a few hours but without result. What I need is when user is logged then everybody will see he is online. I have it already done but problem is when somebody refresh page. Then user is disconnected and connected back and the result is that I have a duplicity instead just update. Here is what I have on server side:



clients = [];

io.on('connection', function (socket) {

if (socket.request.user.username in clients) {

io.emit('chatMessage', {
type: 'status',
text: 'connected',
created: Date.now(),
username: socket.request.user.username,
user_id: socket.request.user._id,
socket_id: socket.id
});


} else {
console.info('New client connected (id=' + socket.id + ').');
// after connect set socket ID to username
clients[socket.request.user.username] = socket.id;


}

socket.on('disconnect', function () {

delete clients[socket.request.user.username];

});
});


On the client side:



angular.module('messages')
.controller('MessagesController', ['$scope', 'Socket', 'Authentication',
function ($scope, Socket, Authentication) {

$scope.authentication = Authentication;

$scope.messages = [];
Socket.on('chatMessage', function (message) {
$scope.messages.push(message);
});
}
]);


And the view:



<section data-ng-controller="MessagesController">
<div data-ng-repeat="message in messages" data-ng-switch="message.type">
<strong data-ng-switch-when='status'>
<span data-ng-bind="message.created | date:'mediumTime'"></span>
<span data-ng-bind="message.username"></span>
<span>is</span>
<span data-ng-bind="message.text"></span>
<span data-ng-bind="message.user_id"></span>
<span>Socket.io ID is </span>
<span data-ng-bind="message.socket_id"></span>
</strong>
</div>
</section>


And result is for example this:



12:08:38 AM jerry.klimcik is connected 5515ce05207842d412c07e03 Socket.io ID je URYiTSu4Zy0In2wNAAAL
12:27:30 AM admin is connected 55156119ec0b97ec217d8197 Socket.io ID is RcP_tyHarb5sN0XoAAAN
12:27:32 AM admin is connected 55156119ec0b97ec217d8197 Socket.io ID is 7dumGFZzgJunF49cAAAO


User admin refreshed page and now I see twice that he is logged. And I want to keep only his last connection. I'm really desperate.


Aucun commentaire:

Enregistrer un commentaire