2017-10-17 69 views
0
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 ...........如何在命名空間socket.io中將客戶端與其他客戶端連接起來?

回答

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'); 
    }  
} 
+0

比你洙多兄弟。 –