简体   繁体   English

在节点js中的Socket.io中为特定用户发出事件

[英]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. 我分别使用socket.onio.emit方法进行请求和响应,目前我遇到了对所有用户都响应的问题。 I want to just notify for particular user . 我只想通知特定用户 But when i asked above question on stackoverflow, someone asked me to follow this link. 但是当我问上述关于stackoverflow的问题时,有人要求我点击链接。 But in above link, It is mentioned that, we need a user Id, which i can get when user login to our app . 但是在上面的链接中,提到了我们需要一个用户ID,当用户登录到我们的应用程序时我可以获取该ID Please have a look at my server.js and router.js file code. 请查看我的server.jsrouter.js文件代码。

router.js 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 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. 在send_personal_message中,您将从数据对象内部的发件人那里收到用户名。 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); io.on('connect',onConnect);

function onConnect(socket){ onConnect(socket)功能{

// sending to the client socket.emit('hello', 'can you hear me?', 1, 2, 'abc'); //发送到客户端socket.emit('hello','你能听到我说话吗?',1,2,'abc');

// sending to all clients except sender socket.broadcast.emit('broadcast', 'hello friends!'); //发送给除发件人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"); //发送给“游戏”房间中的所有客户端,但发送者socket.to('game')。emit('nice 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)"); //发送给'game1'和/或'game2'房间中的所有客户端,除了发送方socket.to('game1')。to('game2')。emit('nice game',“让我们玩一个游戏(太)”);

// sending to all clients in 'game' room, including sender io.in('game').emit('big-announcement', 'the game will start soon'); //发送给“游戏”室中的所有客户,包括发送方io.in('game')。emit('big-announcement','游戏即将开始');

// sending to all clients in namespace 'myNamespace', including sender io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon'); //发送到名称空间“ myNamespace”中的所有客户端,包括发送方io.of('myNamespace')。emit('bigger-announcement','比赛即将开始');

// sending to a specific room in a specific namespace, including sender io.of('myNamespace').to('room').emit('event', 'message'); //发送到特定名称空间中的特定房间,包括发送方io.of('myNamespace')。to('room')。emit('event','message');

// sending to individual socketid (private message) io.to( ${socketId} ).emit('hey', 'I just met you'); //发送到单独的socketid(私人消息)io.to( ${socketId} ).emit('hey','我刚认识你');

// WARNING: socket.to(socket.id).emit() will NOT work, as it will send to everyone in the room // named socket.id but the sender. //警告: socket.to(socket.id).emit()将不起作用,因为它将发送给房间中每个名为socket.id但发送给发送者。 Please use the classic socket.emit() instead. 请改用经典的socket.emit()

// sending with acknowledgement socket.emit('question', 'do you think so?', function (answer) {}); //发送确认信息socket.emit('question','您认为这样吗?',function(answer){});

// sending without compression socket.compress(false).emit('uncompressed', "that's rough"); //发送时不带压缩socket.compress(false).emit('uncompressed',“那很粗糙”));

// 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?'); //发送一条消息,如果客户端尚未准备好接收消息,则该消息可能会被丢弃socket.volatile.emit('maybe','您真的需要吗?');

// specifying whether the data to send has binary data socket.binary(false).emit('what', 'I have no binaries!'); //指定要发送的数据是否具有二进制数据socket.binary(false).emit('what','I no binaries!');

// sending to all clients on this node (when using multiple nodes) io.local.emit('hi', 'my lovely babies'); //发送到该节点上的所有客户端(使用多个节点时)io.local.emit('hi','my lovely babies');

// sending to all connected clients io.emit('an event sent to all connected clients'); //发送给所有连接的客户端io.emit('一个事件发送给所有连接的客户端');

}; };

This is a socket io emit-cheatsheet . 这是一个套接字ocduct-cheatsheet。 one way will be create a ROOM by user unique id and join it . 一种方法是通过用户唯一ID创建ROOM并将其加入。 so whenever you emit something into that ROOM that particular user will get that msg . 因此,每当您向该ROOM中发送某些内容时,该特定用户就会获得该msg。 creating ROOM is easier so later part you can just check that ROOM for user online offline and other work. 创建ROOM更加容易,因此在以后的部分中,您只需检查用户在线和离线工作的ROOM。 This concept can work for one user and multiple users group like watsapp . 这个概念可以像watsapp一样适用于一个用户和多个用户组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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