简体   繁体   中英

Emit event for particular user in Socket.io in node js

I have used method socket.on and io.emit for request and response respectively.Currently I have facing issue that I got response to all users. I want to just notify for particular user . But when i asked above question on stackoverflow, someone asked me to follow this link. But in above link, It is mentioned that, we need a user Id, which i can get when user login to our app . Please have a look at my server.js and router.js file code.

router.js

const express = require('express');
const router = express.Router();
const passport = require('passport');

const userController = require('../controllers/user');

router.route('/auth/login')
  .post(
    userController.login
  );

router.route('/users')
  .get(
    passport.authenticate('jwt', { session: false }),
    userController.getUsers
  );

module.exports = router;

server.js

const express = require('express');
const router = require('./router');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

var server = require('http').Server(app);
var io = require('socket.io')(server);    
server.listen(PORT, () => {
  console.log(`👂\tListening on port ${PORT}!`);
});
app.io = io;
app.use('/api', router);

Note: Can anyone please tell me now, How to emit event for a particular user, if i have registration and login to my app.

Try something like this

let sockets = [];

    io.on("connection", function(socket) {
      socket.on("online", data => {
        socket.name = data.username;
        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);
      });
    });

in send_personal_message you will have receive the username from the sender inside he data object. The following code will be one which will help you to send message o selected user.

socket.to(sockets[data.user]).emit("personal", data);
[https://socket.io/docs/emit-cheatsheet/][1]

io.on('connect', onConnect);

function onConnect(socket){

// sending to the client socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

// sending to all clients except sender socket.broadcast.emit('broadcast', 'hello friends!');

// sending to all clients in 'game' room except sender socket.to('game').emit('nice game', "let's play a game");

// sending to all clients in 'game1' and/or in 'game2' room, except sender socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

// sending to all clients in 'game' room, including sender io.in('game').emit('big-announcement', 'the game will start soon');

// sending to all clients in namespace 'myNamespace', including sender io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

// sending to a specific room in a specific namespace, including sender io.of('myNamespace').to('room').emit('event', 'message');

// sending to individual socketid (private message) io.to( ${socketId} ).emit('hey', 'I just met you');

// WARNING: socket.to(socket.id).emit() will NOT work, as it will send to everyone in the room // named socket.id but the sender. Please use the classic socket.emit() instead.

// sending with acknowledgement socket.emit('question', 'do you think so?', function (answer) {});

// sending without compression socket.compress(false).emit('uncompressed', "that's rough");

// sending a message that might be dropped if the client is not ready to receive messages socket.volatile.emit('maybe', 'do you really need it?');

// specifying whether the data to send has binary data socket.binary(false).emit('what', 'I have no binaries!');

// sending to all clients on this node (when using multiple nodes) io.local.emit('hi', 'my lovely babies');

// sending to all connected clients io.emit('an event sent to all connected clients');

};

This is a socket io emit-cheatsheet . one way will be create a ROOM by user unique id and join it . so whenever you emit something into that ROOM that particular user will get that msg . creating ROOM is easier so later part you can just check that ROOM for user online offline and other work. This concept can work for one user and multiple users group like watsapp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM