0

我一直在 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);
  });
});
4

1 回答 1

0

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

于 2013-01-13T13:24:01.967 回答