从外部文件调用 socket.io API



我正在尝试从另一个express路由的文件调用我的Socket.io接口。假设我想用这个创建以下群聊,然后向群聊中的相关用户发送通知,

路线.js

router.post(
"/save-groupchat",
passport.authenticate("jwt", { session: false }),
(req, res) => {
new GroupChat({
creator: req.user._id,
groupName: req.body.groupName,
groupMembers: userList
})
.save()
.then(newGroup => {
GroupChat.findOne(newGroup)
.populate("groupMembers.user")
.then(groupChat => {
//Notify the user's as well
userList.map((user, key) => {
NotificationCenter.findOneAndUpdate(
{ owner: user.user },
{
$push: {
notifications: {
$each: [
{
type: "group-invite",
title:
"You have been invited to " +
req.body.groupName +
" by " +
req.user.name,
notificationTriggeredBy: req.user._id
}
],
$position: 0
}
}
}
)
.then(() => {
//How do I call the socket here <---------------------------------
console.log("Notified User: " + req.body.userList[key].name);
})
.catch(err => {
console.log(
"Error when inviting: " +
req.body.userList[key].name +
"n " +
err
);
});
});
res.json(groupChat);
});
});
}
);

./微服务/聊天/聊天(套接字接口(

然后我的套接字接口是这样的,

let user_list = {};
io.sockets.on("connection", socket => {
socket.on("send-notification", notification => {
console.log("How do I get here from the other file?");
});
})
...

这是我如何拥有我的server.js文件

var http = require("http").Server(app);
var io = require("socket.io")(http);
ChatMicroservice = require("./microservice/chat/chat")(io);

如何访问套接字接口并使用套接字user_list发送通知?

要从外部文件调用 socket.io API,您应该创建一个单例类并将其导出,或者将套接字对象保存到全局变量中,并将连接的套接字 ID 保存在与用户对应的数据库中。 因此,每当与服务器建立套接字连接时,套接字 ID 即 socket.id 都保存在与 user-id 对应的数据库中。

所以你的套接字接口变成

global.io = io;
io.sockets.on("connection", socket => {
// add your method to save the socket id (socket.id) 
// user-id passed can be accessed socket.handshake.query.userId

socket.on("send-notification", notification => {
console.log("How do I get here from the other file?");
});
})

在您的其他文件调用中

global.io.to(id).emit(event, value);

如果您计划水平扩展应用程序,请在套接字接口中使用socket.io-redis

const redis = require('socket.io-redis');
global.io.adapter(redis({ host: redisUrl, port: redisPort }));

最新更新