在这里添加超级晚,但我想访问我的路由中的一个套接字,并且特别想在保存到数据库后广播一条消息。我使用@aarosil 提供的答案来设置/获取 io 对象,在连接时向每个客户端发送其套接字 id,然后在路由中使用套接字 id 以便能够使用socket.broadcast.emit()
而不是io.emit()
.
在服务器中:
const io = require('socket.io')(server)
app.set('socketio', io)
io.on('connect', socket => {
socket.emit('id', socket.id) // send each client their socket id
})
我使用每个请求发送套接字 id,然后我可以在我的路由中执行以下操作:
router.post('/messages', requireToken, (req, res, next) => {
// grab the id from the request
const socketId = req.body.message.socketId
// get the io object ref
const io = req.app.get('socketio')
// create a ref to the client socket
const senderSocket = io.sockets.connected[socketId]
Message.create(req.body.message)
.then(message => {
// in case the client was disconnected after the request was sent
// and there's no longer a socket with that id
if (senderSocket) {
// use broadcast.emit to message everyone except the original
// sender of the request !!!
senderSocket.broadcast.emit('message broadcast', { message })
}
res.status(201).json({ message: message.toObject() })
})
.catch(next)
})