我尝试了几种尝试发送给连接到特定/命名空间的所有用户,但没有运气。我可能误解了套接字是如何工作的。
但我现在所拥有的是两个浏览器在不同页面上打开。当用户连接到pageA时,该用户现在是' / users'命名空间。当用户连接到pageB时,该用户现在是' / valets'命名空间。
我在pageA上有一个发送到server.js的.emit()。我用.on()监听它,然后尝试运行.emit(),但只运行' / valets'中的用户。命名空间。
我能够在我的终端中看到"听取请求代客"和console.log(数据)部分。
我相信我的问题是usr_nsp.of('/valets').emit("incoming-request",{data:data});
部分。其他注释行是我到目前为止所尝试的。他们都给我一个错误:不是一个功能。
server.js
var app = require('http').createServer();
var io = require('socket.io')(app);
app.listen(3000, function(){
console.log('listening on port 3000');
});
var redis = require('socket.io/node_modules/redis');
// create custom namespace for Users
var room_number;
var usr_nsp = io.of('/users');
usr_nsp.on('connection', function(socket){
console.log('user has connected to /users namespace');
socket.on('request-valet', function(data){
console.log("listening for request valet");
console.log(data);
room_number = data.room_number;
socket.join(room_number);
// usr_nsp.broadcast.of('/valets').emit("incoming-request",{repark:data});
// usr_nsp.of('/valets').broadcast.emit("incoming-request",{repark:data});
// io.of('/valets').emit("incoming-request",{repark:data});
// socket.of('/valets').emit("incoming-request",{repark:data});
usr_nsp.of('/valets').emit("incoming-request",{repark:data});
});
});
var valet_nsp = io.of('/valets');
valet_nsp.on('connection', function(socket){
console.log('valet has connected to /valets namespace');
// var room_number;
socket.on('join-room', function(data){
// assign valet to room
room_number = data.room_number;
socket.join(room_number);
//valet_nsp.sockets.in(room_number).emit("request-accepted",{current_pos:current_pos})
});
socket.on('set-valet-starting-position', function(data){
//var valet_starting_pos = data.starting_position;
valet_nsp.sockets.in(room_number).emit('activate-directions-service', {repark:data});
})
socket.on('get-new-location', function(data){
// send the updated location only to User
// maybe use .broadcast??
valet_nsp.sockets.in(room_number).emit("update-valet-location", {current_pos:data});
});
});
pageB.html(套接字部分)
socket.on('incoming-request', function(data){
console.log("incoming request");
alert("incoming request");
// use data to display on html screen
});
答案 0 :(得分:1)
您创建的命名空间句柄用于emit to users in that particular namespace。因此,这应该有效:
var users = io.of('/users'),
valets = io.of('/valets');
users.on('connection', function(socket) {
socket.on('request-valet', function(data) {
valets.emit('incoming-request', { repark : data });
});
});