我正在用MEAN.js 4.2构建一个应用程序,并且试图使用Socket.io让服务器发出UI将实时响应的特定消息。例如,当服务器向用户的笔记本发布便笺时,笔记本将在用户界面中刷新其内容。在MEAN.js中使用Socket.io命名空间4.2
我想使用命名空间来确保我只向受影响的用户发送事件,并且用户只能监听相关事件。
在服务器上,我有:
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
@bolav他仍然可以在用户进行身份验证时在服务器上创建名称空间,只要在socket.io连接之前发生这种情况... –