【问题标题】:How to send message to specific user using socket_io_client flutter package如何使用 socket_io_client 颤振包向特定用户发送消息
【发布时间】:2020-11-29 20:46:01
【问题描述】:

我正在尝试使用 socket.io 和 node.js 构建一个聊天应用程序,使用 socket.io 和 node.js 作为后端,flutter 用于前端......到目前为止,我一直在尝试向所有连接的用户发送消息,有没有办法将消息发送到特定用户?这是我的后端代码的一部分

io.on('connection', (socket) => {
  console.log(`id: ${socket.id}`)
  socket.on('send_message', (msg) => {
    var detail = JSON.parse(msg)
    socket.in(detail["receiver"]).emit('to_user', msg)
  })
});

在颤振中我正在使用 socket_io_client 包 (https://pub.flutter-io.cn/packages/socket_io_client) 但我不知道如何为特定用户发出消息 这是前端代码的一部分

StreamController<String> _data = StreamController<String>();

  socket.on('send_message', (x) {
      _data.sink.add(x);
  });

  sendChat(String msg, String sender, String receiver) {
    Map map = {"msg": msg, "snd": sender, "rcv": receiver};
    var mapbody = json.encode(map);
    socket.emit('send_message', mapbody);
  }

Stream<String> get sendChat => _data.stream;

【问题讨论】:

    标签: node.js flutter socket.io chat


    【解决方案1】:

    这里有一些选项。

    第一:

    您可以将连接的客户端 ID 存储到 redis。

    使用io-redis

    并在其中存储您的客户 ID: 用于在 redis 中存储 id:

    await redisClient.lpush(`socket_members`, socket.id);
    

    用于获取特定的 id:

    let client = await redisClient.lrange(
                   `socket_members`,
                   0,
                   socket.id
                );
    

    第二个选项是你可以创建一个身份验证中间件

    const jwt = async(socket, next) => {
        let token = socket.handshake.query.token
        let verify = jwt.verify(socket.handshake.query.token, jwt_encryption, async(err, decoded) => {
           // find user with decoded token 
           
            if (!user) {
                return next(new Error(JSON.stringify({ status: 401, message: 'unuthorized' })));
    
            }
            socket.user = user._doc
            return next()
    
        })
    
    };
    

    并在socket io实例中使用它:

    io.use(jwt);
    

    经过身份验证的用户在 socket.user 中。

    希望这会有所帮助

    【讨论】:

    • 您好,感谢您的帮助,您有任何示例如何在flutter的客户端实现第一个选项吗?
    • @uyhaW 看例子
    【解决方案2】:

    你必须有 socket.id 并使用 io.sockets.socket(SocketId).emit(msg) 来发送消息

    var express = require("express");
    var redis = require("redis");
    var sio = require("socket.io");
    var client = redis.createClient()
    var app = express.createServer();
    var io = sio.listen(app);
    io.set("store", new sio.RedisStore); 
    // In this example we have one master client socket 
    // that receives messages from others.
    io.sockets.on('connection', function(socket) {
    // Promote this socket as master
    socket.on("I'm the master", function() {
    // Save the socket id to Redis so that all processes can access it.
    client.set("mastersocket", socket.id, function(err) {
      if (err) throw err;
      console.log("Master socket is now" + socket.id);
    });
    });
    socket.on("message to master", function(msg) {
       // Fetch the socket id from Redis
    client.get("mastersocket", function(err, socketId) {
      if (err) throw err;
      io.sockets.socket(socketId).emit(msg);
    });
    });
    });
    

    【讨论】:

    • 您好,感谢您的帮助...您知道如何从 Flutter 客户端 imolement io.sockets.socket(socketId).emit(msg) 吗?
    猜你喜欢
    • 2014-08-14
    • 2015-04-27
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2017-01-13
    • 2015-11-19
    相关资源
    最近更新 更多