socket.io发送消息两次

时间:2014-06-28 23:06:35

标签: javascript node.js socket.io

我正在尝试在我的SPA应用中创建实时聊天。我让聊天工作,但当我移动到另一个页面并返回聊天页面时,它开始加载消息两次。这是socket.io的服务器端:

var io = require('socket.io').listen(app.listen(config.port));
io.sockets.on('connection', function (socket) {
    socket.emit('message', { message: 'You are chatting now !' });
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });

我尝试使用io.sockets.once而不是io.sockets.on,但它没有第二次显示聊天..

这是我的客户端和html(玉模板引擎):

#content(style='width: 500px; height: 300px; margin: 0 0 20px 0; border: solid 1px #999; overflow-y: scroll;')
    input#field(style='width:350px;')
    input#send(type='button', value='send')
script(src='/socket.io/socket.io.js')
script.
    $("#field").keyup(function(e) {
        if(e.keyCode == 13) {
            sendMessage();
        }
    });
    var messages = [];
    var socket = io.connect('localhost:3030/#/chat');
    var field = document.getElementById("field");
    var sendButton = document.getElementById("send");
    var content = document.getElementById("content");
        socket.on('message', function (data) {
        if(data.message) {
            messages.push(data.message);
            var html = '';
            for(var i=0; i<messages.length; i++) {
                html +=  messages[i] + '<br />';

            }
            content.innerHTML = html;
            content.scrollTop = content.scrollHeight;
        } else {
            console.log("There is a problem:", data);
        }
    });
        sendButton.onclick = sendMessage = function() {
        var text = field.value;
        socket.emit('send', { message: text });
        field.value = '';
    };

我想解决这个问题,所以当我第二次回去时它不会显示2次,或者第3次显示3次等等...非常感谢帮助:)

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望在页面刷新之间保持正确的持久性,只需在服务器上添加一个数组即可收集消息并告知新的连接。

我真的只是使用文档来实现我的目标(链接以供参考http://socket.io/docs/server-api/

要运行以下代码,必须在工作目录中执行这些命令

npm install express
npm install socket.io

(服务器代码)

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

//serve up the file, the code for this is below, I translated your jade to html
app.get('/', function(req, res){
  res.sendfile('index.html');
});

//note this will get big eventually with lots of users
var message_past = [];

io.on('connection', function(socket){
  socket.emit('server-message', { message: 'Welcome !' });
  // tell user recent posts
  for (var i = 0; i < 20 && !!message_past[i] ; i ++) socket.emit('user-message',message_past[i]);

  // save the message and update everyone with it
  socket.on('user-message', function (data) {
        message_past.push(data);
        // io.emit will tell everyone <-- I think what you want
        // socket.broadcast.emit will tell everyone but this socket
        // socket.emit will tell just this socket
        io.emit('user-message', data);
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

和客户端代码

<input id='field' type="text" style='width:350px;'/>
<input id='send' type='button' value='send'/>
<div id='content' style='width: 500px; height: 300px; margin: 0 0 20px 0; border: solid 1px #999; overflow-y: scroll;'>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src='/socket.io/socket.io.js' ></script>
<script type="text/javascript">
    $("#field").keyup(function(e) {
        if(e.keyCode == 13) {
            sendMessage();
        }
    });
    var socket = io.connect('localhost:3000/#/chat');
    console.log(socket)
    var field = document.getElementById("field");
    var sendButton = document.getElementById("send");
    var content = document.getElementById("content");

    var display_message = function( data ) {
        if(data.message) {
            $(content).append(data.message+'<br/>');
            content.scrollTop = content.scrollHeight;
        } else {
            console.log("There is a problem:", data);
        }
    };

   socket.on('server-message', display_message);
   socket.on('user-message', display_message);
   sendButton.onclick = sendMessage = function() {
        var text = field.value;
        socket.emit('user-message', { message: text });
        field.value = '';
    };
</script>