我正在關注Socket.IO tutorial,但我遇到了頁面上顯示的消息數量呈指數增長的問題,使聊天客戶端無效。Socket.io教程創建額外的消息
一些粗略的搜索告訴我,它涉及事件處理程序,但我還沒有發現任何關於如何在這種情況下使用它們的確定性。 什麼和我需要在哪裏使用這些事件處理程序,爲什麼?
我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>
有助於瞭解,但多個消息仍然出現該問題。 – Thassa
@Thassa你需要在'doDid()'之外完全移動'var socket = io()'_and_'socket.on()'。 – robertklep
其實,只要移動你的事件處理即可。您已經綁定到提交事件,不要在提交時調用該函數。在頁面加載時調用它。 – Chad