【问题标题】:Socket.io connection keep increasing each time a new connect has been made每次建立新连接时,Socket.io 连接都会不断增加
【发布时间】:2017-06-14 02:25:43
【问题描述】:

我将 Express4 与指向路径 / 的路由器一起使用,并由名为 chat.js 的 JS 文件处理。

我的 IO 对象已经绑定到app.io,所以在我的chat.js 中,我将使用req.app.io 调用我的Socket.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

【问题讨论】:

  • 您希望发生什么?该控制台输出提示连接、断开连接、连接、连接、断开和断开连接 - 为什么会出错?
  • 如您所见,第一次连接到服务器时,它会注销hellobye 一次,第二次连接到服务器时它会注销@987654335 @ 和 bye 两次
  • 哦,因为对于每个.get('/',您都在添加另一个req.app.io.on('connection',
  • 你注册socket.io事件每个请求/,回调将被追加和console.log将是两次。您可以通过代码而不是代码进行调试:console.log('hello' + uuid);

标签: javascript node.js socket.io express-4


【解决方案1】:

每次您的/ 路由被命中时,您都会创建一个新的重复io.on('connection', ...) 事件处理程序。因此,在该路由被击中 3 次后,您就有了 3 个用于 connection 事件的事件处理程序。因此,当它发生时,您的代码会被调用 3 次。

相反,您应该只在路线外执行一次io.on('connection', ...)


仅供参考,您似乎没有对您正在创建的uid 做任何有用的事情,因为您没有将它与任何特定连接相关联。仅供参考,每个 socket.io 连接已经有一个唯一的socket.id,它与每个 socket.io 连接唯一关联,这样您就可以从套接字获取 id 或仅检索给定 id 的套接字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多