dbOperations.saveRequest(db, requestId, requestTime, location, eventData.citizenId, 'waiting', function(results) {
//2. AFTER saving, fetch nearby cops from citizen’s location
dbOperations.fetchNearestCops(db, location.coordinates, function(results) {
eventData.requestId = requestId;
//3. After fetching nearest cops, fire a 'request-for-help' event to each of them
for (var i = 0; i < results.length; i++) {
io.sockets.in(results[i].userId).emit('request-for-help', eventData);
}
});
});
});
我想将活动发送给特定的警察但不是全部......... 我并没有完全了解io.socket.in如何工作可以任何人建议我aproper参考继续plzzzzzzz ............
答案 0 :(得分:0)
基本上我们在项目中所做的是创建了一个层,用于管理userId和socketId之间的一对一映射。因此,每当连接用户套接字时,我们首先注册该用户,因此该层添加userId到socketId的映射,当用户断开连接时,我们删除了基于socketId的映射。
因此,如果要发送给用户,请将此userId传递给此图层,如果映射到socketId将发送此图层。
<强>伪代码强>
var userMap ={};
var socketMap ={};
io.sockets.on('connection', function(socket) {
socket.on('register', function(userId, cb) {
/*Our custom event, which on basis of userId add mapping between user and socketid*/
userMap[userId] = socket.id; //save user
socketMap[socket.id] = userId; //save socket
});
socket.on('disconnect', function(userId, cb) {
/*When socket disconnect, remove mapping*/
delete userMap[socketMap[socket.id]]; //remove user
delete socketMap[socket.id]; //remove socket
});
});
/*Function used to send message*/
function sendMessage(userId){
if(userMap[userId]){
io.to(userMap[userId]).emit('message');
}
}