我将 Express4 与指向 path 的路由器一起使用/
,并且由名为 .js 的 JS 文件处理chat.js
。
而且我的 IO 对象已经绑定到app.io
,所以在我的内部我chat.js
将通过 using 调用我的 Socket.IO req.app.io
,但问题是,我曾经使用过socket.emit
并且代码工作正常,但现在如果我想与我必须使用的客户端req.app.io.emit
。
而且因为我正在使用req.app.io.emit
,所以我的连接问题不断增加。
index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const path = require('path');
const randomstring = require('randomstring');
const sha256 = require('sha256');
const io = require('socket.io').listen(server);
app.io = io;
const port = process.env.PORT || 3000;
module.exports.users = {};
server.listen(port, () => {
console.log(`Serer is running on port ${port}`);
});
app.set('view engine', 'ejs');
app.set('views', path.join(`${__dirname}/../public`));
app.use('/static', express.static(path.join(`${__dirname}/../public`)));
app.use('/', require('./chat'));
聊天.js
const express = require('express');
const router = express.Router();
const users = require('./index').users;
const randomstring = require('randomstring');
router.get('/', (req, res) => {
res.render('index');
const uid = randomstring.generate(30);
users[uid] = true;
req.app.io.on('connection', socket => {
console.log('hello');
socket.on('disconnect', () => {
console.log('bye');
});
});
});
module.exports = router;
日志(图像)
Serer is running on port 3000
hello
bye
hello
hello
bye
bye