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

Socket.io服务器返回消息数组异常:数量缺失且延迟的问题求助

Socket.io消息回传异常问题修复

问题现象

输入消息后,服务器回传消息存在异常:

  • 首次输入消息,服务器返回空数组
  • 再次输入消息,返回数组仅包含上一条历史消息,消息数量始终比实际输入少1条

问题原因

  1. 客户端状态更新异步问题:React的setAllInfo是异步操作,调用sendChatToServer时,allInfo仍为更新前的旧值,导致传给服务器的数组缺少当前新消息。
  2. 服务器拼写错误:判断条件中的chat.lenght应为chat.length,首次传入数组时因判断不成立,未触发消息回传逻辑。

修复方案

客户端代码修改

使用React函数式状态更新获取最新的allInfo,确保发送给服务器的是包含新消息的完整数组:

'use client'

import { io } from 'socket.io-client'
import { useEffect, useState } from 'react'
import { ChatSenderBox } from './ChatBox'
import { ChatRecieverBox } from './ChatBox'
import MessageInput from './MessageInput'


const ChatContainer = ({username, userImage}) => {

  const [socket, setSocket] = useState(undefined)
  const [allInfo, setAllInfo] = useState([])

  const sendChatToServer = (chat) => {
    socket.emit('chat', chat)
  }

  useEffect(()=>{
    const socket = io('http://localhost:3001')

    socket.on('chat', (chatRecieved) => {
      setAllInfo(chatRecieved)
    })

    setSocket(socket)
  }, [])

  const addMessage = (chat) => {
    const newChat = {...chat, username, userImage}

    if(newChat.message.trim() !== ''){
      // 函数式更新获取最新状态
      setAllInfo(prevState => [...prevState, newChat])
      // 基于最新状态生成完整数组发送给服务器
      sendChatToServer(prevState => [...prevState, newChat])
    } 
  }

  const ChatsArrangement = ({ data, username }) => {
    return data.map((info, index) => {
      return username === info.username ? (
        <ChatSenderBox 
          key={index} 
          username={info.username} 
          profilePic={info.userImage} 
          message={info.message} 
        />
      ) : (
        <ChatRecieverBox 
          key={index} 
          username={info.username} 
          profilePic={info.userImage} 
          message={info.message} 
        />
      )
    })
  };

  return (
    <>
      <div className=' w-full h-full p-4 chatPage z-100'>
        {allInfo.length > 0 && <ChatsArrangement data={allInfo} username={username}/>}
      </div>
      <MessageInput addMessage={addMessage}/>
    </>
  )
}

export default ChatContainer

服务器代码修改

修正拼写错误lenght为length,确保消息能正常触发回传:

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

const server = http.createServer(app)
const io = new Server(server, {
    cors:{
        origin: 'http://localhost:3000',
        methods: ["GET", "POST"]
    }
})

io.on("connection", (socket) => {
    console.log("A user is connected")

    socket.on("chat", (chat)=>{
        // 修正拼写错误:lenght -> length
        if(chat.length){
            io.emit("chat", chat)
        }
        console.log(chat)
    })

    socket.on("disconnect", ()=>{
        console.log("A user disconnected")
    })
})

server.listen(3001, () => console.log('listening to port 3001'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:35:15