我知道那里有很多答案,但在我的用例中,它有点令人困惑。我只是想看看我的解决方案是否足够好
当用户A从用户B购买某些内容时,我的用例非常简单,将创建两个用户的聊天室。
从技术上讲,要去那个房间,买家或卖家必须使用
的APIapp.get('/room/:roomid', (req, res, next) => {
// Find the appropriate room using mongoose/mongodb to show relevant data to this HTML page
Room.findOne({_id: req.params.roomid }, function(err, room) {
// Show some data on the HTML page using Handlebars or EJS
});
});
这只是处理买家和卖家的房间页面。
我的困惑在于让两个用户加入房间。在API上,我应该运行socket.join吗?例如
app.get('/room/:roomid', (req, res, next) => {
// Whenever someone comes to this room, do
socket.join(req.params.roomid); // Will this work?
Room.findOne({_id: req.params.roomid }, function(err, room) {
});
});
假设有可能在API级别上使用socket.join(可能需要使用redis或其他东西,因为它在socket.io环境之外)
我应该使用session to socket.io环境发送roomid吗?
API的更新版本
app.get('/room/:roomid', (req, res, next) => {
const roomid = req.params.roomid;
socket.join(roomid);
req.session.roomid = roomid;
Room.findOne({_id: req.params.roomid }, function(err, room) {
});
});
在socket.io环境
上io.on('connection', function(socket) {
// This will trigger, when user submit on the input box
socket.on('chatTo', (data) => {
// Sending to the appropriate room.
io.to(socket.request.session.roomid).emit('incomingChat', {
data
});
});
});
我的目标很简单,买家从卖家那里买东西,创建聊天室,每当买家或卖家碰到聊天室api时,其中任何一个都会加入房间,因此可以互相发送消息,因为房间是唯一的。
我的解决方案是否足够有效还是有更好的方法来正确处理这个问题?