我真的需要帮助来解决我遇到的socket.io问题。相信我,我几乎浏览了有关该主题的每篇文章...
App.js
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('User Disconnected');
});
socket.on('example_message', (msg) => {
console.log('message: ' + msg);
});
});
app.set('socketio', io);
const port = process.env.PORT || 7777;
app.listen(port);
console.log(`Server listening at ${port}`);
module.exports = app;
Routes.js
const express = require('express');
const router = require('express-promise-router')();
router.route('/test-route')
.put(TestController.testEmit);
module.exports = router;
TestController.js
module.exports = {
testEmit: async (req, res, next) => {
const io = req.app.get("socketio");
console.log(io); // this ACTUALLY logs the entire socketio object!
io.emit('example_message', 'abc'); // NOTHING HAPPENS
}
}
每次重新加载客户端时,都会在终端窗口中看到“用户已连接”。但是,当我尝试从testEmit控制器发出信号时,什么也没有发生。