Socket.io教程创build额外的消息

我正在关注Socket.IO教程 ,但我遇到了一个问题,即页面上显示的消息数量呈指数级增长,导致聊天客户端无效。

一些粗略的search告诉我,它涉及事件处理程序,但我还没有发现任何关于如何在这种情况下使用它们的确定性。 什么和我需要在哪里使用这些事件处理程序,为什么?

我的index.js:

var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ // console.log('a user connected'); // socket.on('disconnect', function(){ // console.log('user disconnected'); // }); socket.on('chat message', function(msg){ //console.log('message: ' + msg); io.emit('chat message', msg); }); }); http.listen(8080, function(){ console.log('listening on *:8080'); }); 

和我的HTML:

 <!doctype html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <script src="/socket.io/socket.io.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> function doDid(){ var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); }; </script> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button onclick="doDid()">Send</button> </form> </body> </html> 

问题是,每次按下button时,都会订阅“聊天消息”事件。

你应该只运行一次这个代码:

  var socket = io(); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); 

所以你应该像这样改变你的代码:

 <script> var socket = io(); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); function doDid(){ $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); }; </script> 
 var socket = io(); 

这一行创build一个到socket.io的连接。 每当你打电话给你时,你正在创build另一个连接。 尝试只调用一次,而不是每次发送。

为了澄清, io()函数是一个工厂而不是一个访问器

编辑

看起来像socket.io客户端实际上是创buildcaching套接字,并不创build多个连接。

不过,我也注意到你在这个函数中绑定了事件,但是每次点击都会调用它,所以你每次都在重新绑定。 在启动时只调用一次你的函数。