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

基于Socket.io与Node.js的聊天应用问题:消息追加及连接异常

Hey there, let's work through your Socket.io chat app issues step by step. I see three main problems here, and we'll tackle them starting with the one you care most about: getting the chat.append() functionality working correctly.


1. Fixing Message Display (Your Core Issue)

The biggest blocker here is a simple typo in your client-side script, plus an incorrect element being appended:

  • You tried to select the chat area with $('#char'), but your HTML uses the ID chat (missing a t).
  • You were appending a <ul> element instead of the <div class="well"> you intended for messages.

Corrected Client-Side Script Snippet:

<script src="/socket.io/socket.io.js"></script>
<script>
$(function(){
  var socket = io.connect();
  var $messageForm = $('#messageForm');
  var $message = $('#message');
  var $chat = $('#chat'); // Fixed typo from 'char' to 'chat'

  $messageForm.submit(function (e) {
    e.preventDefault();
    console.log('submitted');
    socket.emit('send message', $message.val());
    $message.val('');
  });

  socket.on('new message', function(data){
    $chat.append('<div class="well">' + data.msg + '</div>'); // Append the correct well-formatted div
  });
});
</script>

2. Fixing Duplicate Connections & Failed Socket Removal on Disconnect

Your server-side disconnect logic had two critical errors:

  • You were listening for disconnection (wrong event name) on the global io instance instead of the individual socket object. The correct event name is disconnect.
  • You used slice() which returns a new subarray but doesn't modify the original connections array. Use splice() instead to remove the socket from the array.

Corrected Server-Side Connection/Disconnect Logic:

io.on('connection', function(socket){
  connections.push(socket);
  console.log('connected: %s sockets connected', connections.length);

  // Fix: Listen for disconnect on the individual socket, use splice to remove it
  socket.on('disconnect', function(){
    connections.splice(connections.indexOf(socket), 1);
    console.log('disconnected: %s sockets connected', connections.length);
  });

  // send message
  socket.on('send message', function (data){
    console.log(data);
    io.sockets.emit('new message', {msg: data});
  });
});

This fixes both the duplicate connection records on page refresh (old sockets will trigger disconnect when the page reloads) and ensures sockets are properly removed from the connections array.


3. Bonus: Minor Form Improvement

Your textarea has a name="name" attribute which doesn't match its purpose (it's for message content). While this doesn't break functionality, updating it makes your code more readable:

<textarea class="form-control" id="message" name="message" rows="8" cols="80"></textarea>

Full Modified Server Code (server.js)

var http = require('http');
var express = require('express'), app = module.exports.app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

let users = [];
let connections = [];

console.log('Server running...');
app.get('/', function (req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  connections.push(socket);
  console.log('connected: %s sockets connected', connections.length);

  socket.on('disconnect', function(){
    connections.splice(connections.indexOf(socket), 1);
    console.log('disconnected: %s sockets connected', connections.length);
  });

  socket.on('send message', function (data){
    console.log(data);
    io.sockets.emit('new message', {msg: data});
  });
});

server.listen(80);

After applying these changes, your messages will display correctly in the well-formatted divs, connection counts will stay accurate on refresh/disconnect, and the core chat.append() functionality will work as intended.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:58:11