0

我正在尝试设置 socket.io,但我遇到了 90% 的问题。我正在运行我的服务器,它说它已连接,然后我会在 2-3 秒后收到一连串新客户端。这是我的终端输出:

21 Dec 17:36:53 - socket.io ready - accepting connections
21 Dec 17:37:13 - Initializing client with transport "websocket"
21 Dec 17:37:13 - Client 4786583543755114 connected
21 Dec 17:37:18 - Client 4786583543755114 disconnected
21 Dec 17:37:18 - Initializing client with transport "xhr-polling"
21 Dec 17:37:18 - Client 377916906028986 connected
21 Dec 17:37:18 - Initializing client with transport "xhr-polling"
21 Dec 17:37:18 - Client 3885312571655959 connected
21 Dec 17:37:18 - Initializing client with transport "xhr-polling"
21 Dec 17:37:18 - Client 38271573395468295 connected

每 1-2 秒还有更多。我正在使用支持 websockets 的 safari,这在第一个响应中很明显。

这是我的服务器代码:

server = http.createServer(function(req, res){ 
    // your normal server code 
    res.writeHead(200, {'Content-Type': 'text/html'}); 

    var path = url.parse(req.url).pathname; 

    // console.log(__dirname + path);
    fs.readFile(__dirname + path, function(error, data) {
        res.end(data); 
    }); 


});

server.listen(80);

// socket.io, I choose you
var socket = io.listen(server);

socket.on('connection', function(client){
    // new client is here!
    client.on('message', function(){  });
    client.on('disconnect', function(){  });
});

..和客户端代码:

    <script> 

        var socket = new io.Socket();
        socket.connect();

        socket.on('message', function(obj){
            alert('got some data ' + obj);
        });

        socket.on('connect', function() {
            console.log("We've connected!");
            socket.send('some data');
        })


    </script>

任何线索或帮助都会很棒。谢谢!

4

1 回答 1

2

好吧,事实证明这是一个非常小的修复,它使一切变得不同 - 不要忘记将 HTML5 文档类型添加<!doctype html>到客户端的顶部!

于 2010-12-22T00:47:12.210 回答