Socket.io有人可以帮助我为什么连接/断开消息出现两次?

下面是我的服务器端代码,我想要显示,如果用户连接或断开。但用户连接和用户断开消息出现两次。 有人能帮我吗为什么出现两次?

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

客户代码

 <!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> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); </script> <script src="/socket.io/socket.io.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> 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> <script> var typing = false; var timeout = undefined; function timeoutFunction(){ typing = false; socket.emit(noLongerTypingMessage); } function onKeyDownNotEnter(){ if(typing == false) { typing = true socket.emit(typingMessage); timeout = setTimeout(timeoutFunction, 3000); } else { clearTimeout(timeout); timeout = setTimeout(timeoutFunction, 3000); } } </script> </body> </html> 

你在客户端文件中有两个这样的副本:

 script src="/socket.io/socket.io.js"></script> <script> var socket = io(); </script> 

删除其中的一个。

纠正您的订单

 io.on('connect', function(socket) { socket.broadcast.emit('chat message', 'a user connected!'); socket.on('chat message', function(msg) { socket.broadcast.emit('chat message', msg); }); socket.on('disconnect', function() { socket.broadcast.emit('chat message', 'user disconnected'); }); });