私は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()'と 'socket.on()'を動かす必要があります。 – robertklep
実際には、イベント処理を移してください。すでに送信イベントにバインドしていますが、送信時にその関数を呼び出さないでください。ページの読み込み時に呼び出します。 – Chad