【发布时间】:2016-06-17 07:30:45
【问题描述】:
我正在使用 MEAN.js 4.2 构建应用程序,并尝试使用 Socket.io 让服务器发出 UI 将实时响应的某些消息。例如,当服务器向用户的 Notebook 发布 Note 时,Notebook 将在 UI 中刷新其内容。
我想使用命名空间来确保我只将事件发送给受影响的用户,并且用户只收听相关事件。
在服务器上,我有:
var namespace = '/player-' + user._id; // whereas user._id is the user's unique id
var nsp = io.of(namespace);
nsp.emit('note.posted', note); // whereas note contains info about the posted note
然后,在客户端控制器上:
angular.module('myapp')
.controller('NotebookController', ['$scope', '$state', '$stateParams', '$http', 'Authentication', 'Notebook', 'Socket', function ($scope, $state, $stateParams, $http, Authentication, Notebook, Socket) {
...
var nsp = '/player-' + Authentication.user._id; // This gives me the same namespace as used on the server. I just don't know what to do with it.
if (!Socket.socket) {
Socket.connect();
}
Socket.on('note.posted', function (data) {
$scope.find(); // this just refreshes the list of notes in the UI
});
$scope.$on('$destroy', function () {
Socket.removeListener('note.posted');
});
...
所以,客户端命名空间仍然是“/”,因为我没有在任何地方连接到其他命名空间。确实,我在设置监听器时验证了 Socket.socket.nsp = '/'。
如果我在默认命名空间中发出事件,则一切正常...除了事件发送到连接到默认命名空间的每个客户端。
有什么想法吗?
【问题讨论】:
-
你试过
Socket.connect(nsp)吗? -
@mef:socket.io 不支持动态命名空间,所以你必须在连接客户端之前在服务器上创建命名空间。
-
@bolav 他仍然可以在用户进行身份验证时在服务器上创建命名空间,只要这发生在 socket.io 连接之前...
-
@mef:正如我所说,无论如何这似乎是滥用,因为他的用例也可以使用房间。
标签: angularjs node.js socket.io mean-stack meanjs