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

基于Socket.IO与MySQL存储的chat_id创建专属聊天室实现同房间通信

实现方案

1. 前端聊天室页面调整

用户跳转进入/chat/[chat_id]页面后,先从URL提取当前聊天室ID,触发加入房间事件:

const socket = io('http://localhost:4001');
// 从路径中提取chat_id
const chatId = window.location.pathname.split('/')[2];
// 向服务端发送加入房间请求
socket.emit('joinRoom', chatId);

// 发消息时携带chat_id参数
function sendMessage(msgContent, userId) {
  const msg = {
    chat_id: chatId,
    content: msgContent,
    sender_id: userId
    // 其他你需要的消息字段
  };
  socket.emit('newMessage', msg);
}

你原有getId方法的跳转逻辑无需修改,跳转至聊天室页面后执行上述代码即可。

2. 服务端新增房间校验&加入逻辑

补全chats.js的initChatSocket方法,先校验聊天室真实存在,再将用户加入对应房间:

const { Chat } = require('../../models/Chat');

function initChatSocket(socket, io) {
  socket.on('joinRoom', async (chatId) => {
    // 校验数据库中是否存在该聊天室
    const existChat = await Chat.findByPk(chatId);
    if (!existChat) {
      socket.emit('errorMsg', '聊天室不存在');
      return;
    }
    // Socket.IO会自动创建不存在的房间,直接调用join即可
    await socket.join(chatId);
    // 可选:向房间内其他用户发送加入通知
    socket.to(chatId).emit('systemMsg', `新用户加入聊天室:${existChat.chat_name}`);
  });
}

module.exports = { initChatSocket };

3. 修改消息发送逻辑,限制仅同房间接收

修改messages.js的消息推送逻辑,将原全局广播改为指定房间推送:

const { Message } = require('../../models/Message');

function initMessagesSocket(socket, io) {
  socket.on('newMessage', async msg => {
    try {
      // 注意:你的Message模型需要新增chat_id字段,关联Chat表的id字段
      const createMessage = await Message.create(msg);
      const plainMsg = createMessage.get({ plain: true });
      // 仅将消息推送给对应chat_id房间的所有用户,包括发送者自己
      io.to(msg.chat_id).emit('message', plainMsg);
    } catch (e) {
      console.log(e);
      socket.emit('errorMsg', '消息发送失败');
    }
  });
}

补充说明

  • 如需拉取聊天室历史消息,可新增接口根据chat_id查询Message表中对应数据返回即可
  • 如果需要限制只有有权限的用户才能进入指定聊天室,可在joinRoom事件中新增用户权限校验逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:45:03