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

基于Node.js和Socket.io的Web聊天应用连接问题求助

Node.js + Socket.io 聊天应用连接问题排查

我正在开发一个基于Node.js和Socket.io的简单Web聊天应用,目前卡在Socket与服务器的连接问题上。以下是服务端、客户端代码,以及错误截图,恳请协助排查:

服务端代码

// const { Socket } = require('socket.io')

// Node server
const io=require('socket.io')(8000)

const user={}

// connection come  // user joined 
// socket.io instance which listen all the connection (new user joined )
io.on('Connection',socket=>{  
    // basically used for particular joint connection  
    // user joint event this function will run 
    socket.on('new-user-joined', name=>{
      console.log('New User Joined',name);
      user[socket.id]=name;     // update user  
      // dispaly to all connection in the group 
      socket.broadcast.emit('user-joined',name);
    });

    socket.on('send' , socket=>{
       socket.broadcast.emit('receive',{message:message, name: user[socket.id]})
    }); 
})

客户端代码

const socket=io('http://localhost:8000') 
const form=document.getElementById('send_container')
const messageInput=document.getElementById('messageinp') 
const messageContainer= document.querySelector(".container")


let name=prompt("Enter your name to join");
socket.emit('new-user-joined' ,name);

错误截图

连接错误截图


问题排查与修正方案

  • 服务端连接事件名错误:Socket.io的连接监听事件是小写的connection,你写成了大写开头的Connection,导致服务器无法捕获客户端的连接请求,这是核心问题。修改为:
    io.on('connection', socket => {
      // ... 原有逻辑
    });
    
  • 服务端send事件回调参数错误:回调里把参数命名为socket(和外层的socket变量冲突),且未定义message变量,正确写法应该是接收客户端发送的消息内容:
    socket.on('send', message => {
      socket.broadcast.emit('receive', { message: message, name: user[socket.id] })
    });
    
  • 客户端需确保引入Socket.io库:在HTML页面中添加客户端库的引用,要么使用服务器提供的内置文件:
    <script src="/socket.io/socket.io.js"></script>
    
    要么使用CDN链接(版本可根据实际调整):
    <script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:50:42