2016-05-12 48 views
1

我正在關注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> 

回答

1

問題是,您每次按下按鈕時都會訂閱「聊天消息」事件。

您應該只運行這段代碼一次:

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> 
1
var socket = io(); 

該行創建於socket.io的連接。每次你打電話給你時,你正在創建另一個連接。嘗試只調用一次,而不是每次發送。

爲了澄清,所述io()函數是工廠不是存取

編輯

貌似socket.io客戶實際上做緩存插座創建並不會創建多個連接。

但是,我也注意到你在這個函數中綁定了事件,但是每次點擊都會調用它,所以你每次都在重新綁定。在啓動時只調用一次你的函數。

+0

有助於瞭解,但多個消息仍然出現該問題。 – Thassa

+0

@Thassa你需要在'doDid()'之外完全移動'var socket = io()'_and_'socket.on()'。 – robertklep

+0

其實,只要移動你的事件處理即可。您已經綁定到提交事件,不要在提交時調用該函數。在頁面加載時調用它。 – Chad