我正在尝试使用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;
答案 0 :(得分:0)
您必须拥有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);
});
});
});
答案 1 :(得分:0)
这里有一些选项。
第一:
您可以将连接的客户端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 中。
希望这会有所帮助