我在几个小时内解决了这个问题但没有结果。我需要的是当用户登录时,每个人都会看到他在线。我已经完成了但问题是当有人刷新页面时。然后用户断开连接并返回连接,结果是我有一个双重性而不只是更新。这是我在服务器端的内容:
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
刷新页面,现在我看到他被记录了两次。我只想保留他最后的联系。我非常绝望。
答案 0 :(得分:1)
如果我理解你的问题,那么事实是你在创建用户时而不是在创建用户之后发送连接消息。
因此,这个块:
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;
}
应该被这样的东西取代:
if (!clients.hasOwnProperty(socket.request.user.username)) {
console.info('New client connected (id=' + socket.id + ').');
// after connect set socket ID to username
clients[socket.request.user.username] = socket.id;
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
});
}
然后,客户端的会话依赖于他的用户名。