2016-03-03 44 views
2

我正在用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 ='/'。

如果我在默认命名空间中发出事件,那么一切都很完美......除了事件发生在连接到默认命名空间的每个客户端之外。

任何想法?

+0

您是否尝试过'Socket.connect(NSP)'? –

+0

@mef:socket.io不支持动态命名空间,因此您必须在与客户端连接之前在服务器上创建命名空间。 – bolav

+0

@bolav他仍然可以在用户进行身份验证时在服务器上创建名称空间,只要在socket.io连接之前发生这种情况... –

回答

1

Socket.IO中的命名空间并不意味着使用动态,就像你在这里所做的那样。它看起来更像是在一台服务器上运行不同的应用程序。

你应该使用的是房间。

Server代码

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 
+0

谢谢!我只是在阅读命名空间和房间的比较,并开始得出这个结论。我会试试这个... – Foswick

+0

太棒了!发现!这也更安全,因为我可以管理服务器上的访问。 – Foswick