Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 在MEAN.js 4.2中使用Socket.io命名空间_Angularjs_Node.js_Socket.io_Mean Stack_Meanjs - Fatal编程技术网

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

Angularjs 在MEAN.js 4.2中使用Socket.io命名空间,angularjs,node.js,socket.io,mean-stack,meanjs,Angularjs,Node.js,Socket.io,Mean Stack,Meanjs,我正在用MEAN.js 4.2构建一个应用程序,并尝试使用Socket.io让服务器发出UI将实时响应的某些消息。例如,当服务器向用户的笔记本发布便笺时,笔记本将刷新其在UI中的内容 我想使用名称空间来确保我只向受影响的用户发送事件,并且用户只侦听相关事件 在服务器上,我有: var namespace = '/player-' + user._id; // whereas user._id is the user's unique id var nsp = io.of(namespace);

我正在用MEAN.js 4.2构建一个应用程序,并尝试使用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中的名称空间不应该像您在这里所做的那样动态使用。看起来更像是在一台服务器上运行不同的应用程序

你应该使用的是房间

服务器代码

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 

非常感谢。我刚刚阅读了名称空间和房间的比较,并开始得出这个结论。我会试试这个…太棒了!完全正确这也更安全,因为我可以管理服务器上的访问。您是否尝试过
Socket.connect(nsp)
?@mef:Socket.io不支持动态命名空间,因此您必须在与客户端连接之前在服务器上创建命名空间。@bolav当用户进行身份验证时,他仍然可以在服务器上创建命名空间,只要这发生在socket.io连接之前…@mef:正是我所说的,不管怎么说,这似乎是滥用,他的用例也可以使用房间。