【发布时间】:2015-03-30 22:36:35
【问题描述】:
我解决了这个问题几个小时,但没有结果。我需要的是当用户登录时,每个人都会看到他在线。我已经完成了,但问题是当有人刷新页面时。然后用户断开连接并重新连接,结果是我有重复而不是更新。这是我在服务器端的内容:
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];
});
});
在客户端:
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);
});
}
]);
还有观点:
<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>
结果例如是这样的:
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
用户admin 刷新页面,现在我看到两次他已登录。我只想保留他最后的联系。我真的很绝望。
【问题讨论】:
标签: angularjs node.js sockets express socket.io