在MEAN.js中使用Socket.io命名空间4.2

我正在用MEAN.js 4.2构build一个应用程序,并试图使用Socket.io让服务器发出一些UI将实时响应的消息。 例如,当服务器向用户的笔记本发布注释时,笔记本将在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.IO中的命名空间并不是用来dynamic的,就像你在这里所做的那样。 它看起来更像是在一台服务器上运行不同的应用程序。

你应该使用的是房间。

服务器代码

 var room = 'player-' + user._id; // whereas user._id is the user's unique id io.on('connection', function(socket){ socket.join(room); }); // This is to send the note io.to(room).emit('note.posted', note); // whereas note contains info about the posted note