断开连接时才能看到结果

时间:2012-02-25 11:26:11

标签: node.js socket.io disconnect

我一直在使用VPS上的node.js / socket.io,试图做一个基本的发送和放大器。接收。似乎授权好了,而且我在VPS上得到了这个:websocket writing 5:::{"name":"news","args":[{"hello":"world"}]}虽然我在断开连接时只看到客户端上的任何内容。他们断开连接后,我会显示“世界”这个词。我做错了什么,我不应该在他们仍然连接的时候看到这个词吗?谢谢您的帮助。

我正在使用此代码:

客户端:

<!doctype html>
<html>
<head>
<title>web sockets</title>
<meta charset="utf-8">
<script src="http://IP-ADDRESS/socket.io/socket.io.js"></script>
<script>
var socket = io

.connect('http://IP-ADDRESS:80');
    socket.on('news', function (data) {
        console.log(data);
        writeMessage(data);
        socket.emit('my other event', { my: 'data' });
    });

    function writeMessage(msg) {
        var msgArea = document.getElementById("msgArea");
        if (typeof msg == "object") {
            msgArea.innerHTML = msg.hello;
        }
        else {
            msgArea.innerHTML = msg;
        }
    }
    </script>
    </head>
    <body>
    <div id="msgArea">
    </div>
    </body>
    </html>

服务器

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

1 个答案:

答案 0 :(得分:0)

一年后,我现在正在使用纯网箱。我最终得到了socket.io(不记得这里的问题是什么),但它没有按照我想要的方式工作。 Websockets工作得很好。