基于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 IDchat(missing at). - 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 globalioinstance instead of the individualsocketobject. The correct event name isdisconnect. - You used
slice()which returns a new subarray but doesn't modify the originalconnectionsarray. Usesplice()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

