You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实时协作IDE后端Nodemon服务器频繁崩溃问题求助

解决Node.js Socket.io服务器崩溃问题

你的服务器持续崩溃是由两处明显的代码错误导致的,以下是具体问题和修复方案:

1. 函数参数拼写错误

在getAllConnectedClients函数中,你将参数roomId误写为rommId,这会导致无法正确获取指定房间的Socket连接列表,调用该函数时直接抛出错误。

修复后的函数:

const getAllConnectedClients = (roomId) => {
    return Array.from(io.sockets.adapter.rooms.get(roomId) || []).map(
        (socketId) => {
            return {
                socketId,
                username: userSocketMap[socketId],
            };
        }
    );
};

2. 环境变量读取错误

代码中process.nextTick.PORT是完全错误的写法,nextTick是Node.js的异步执行方法,并非存储环境变量的对象。正确读取端口环境变量的方式是process.env.PORT,错误写法会导致端口读取异常,进而引发服务器运行错误。

修复后的端口定义:

const PORT = process.env.PORT || 5000;

完整修复后的代码

const express = require("express");
const app = express();
const http = require('http');
const {Server} = require('socket.io');

const server = http.createServer(app);
const io = new Server(server);

const userSocketMap = {};

const getAllConnectedClients = (roomId) => {
    return Array.from(io.sockets.adapter.rooms.get(roomId) || []).map(
        (socketId) => {
            return {
                socketId,
                username: userSocketMap[socketId],
            };
        }
    );
};

io.on("connection", (socket) => {
    socket.on("join", ({ roomId, username }) => {
        userSocketMap[socket.id] = username;
        socket.join(roomId);
        const clients = getAllConnectedClients(roomId);
        console.log(clients);
    });
});

const PORT = process.env.PORT || 5000;
server.listen(PORT, () => console.log('server is running on port', PORT));

内容的提问来源于stack exchange,提问作者Divyansh Pathak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:03:17