I've been trying to implement a chat service using socketio. I need to set a message to a selected socket id. The documentation says to use a function like socket.to(<socketid>).emit('hey', 'I just met you');
But it doesnt seem to be working. few moths ago i achieved this functionality by a function like io.sockets.connected[<socketid>].emit('hey', 'I just met you');
but now it doesnt seem to work any more. Btw the socket.broadcast.emit();
works pretty well. How to resolve this issue?
Manage to send private message by the following code.
io.on("connection", function(socket) {
socket.on("online", data => {
socket.name = data.username;
onlineUsers.push(data);
sockets[data.username] = socket.id;
});
socket.on("message", function(data) {
socket.broadcast.emit("public", data);
});
socket.on("send_personal_message", function(data) {
socket.to(sockets[data.user]).emit("personal", data);
});
socket.on("disconnect", reason => {
sockets.splice(sockets.findIndex(id => id === socket.id), 1);
});
});