【问题标题】:Simple nodeJS example not working with socket.io简单的 nodeJS 示例不适用于 socket.io
【发布时间】:2014-07-01 17:01:55
【问题描述】:

整天都在努力尝试使用 socket.io 使这个简单的示例工作。我最初在 Windows 7 上使用 Cygwin 进行了尝试。此后也在 OS X 上进行了尝试,结果相同。

运行脚本时,它会显示这个...

2 May 20:57:47 - socket.io ready - accepting connections

但是访问 index.html 页面并没有显示客户端已经连接。

index.html

<html>
<head>
<script type="text/javascript" src="socket.io.js"></script> 
<script type="text/javascript"> 
    var socket = new io.Socket('localhost',{'port':8090});

    socket.connect();

    socket.on('connect', function(){
        console.log('connected');
        socket.send('hi!'); 
    });

    socket.on('message', function(data){ 
        console.log('message recived: ' + data);
    });

    socket.on('disconnect', function(){
        console.log('disconected');
    });
</script> 
</head>
<body></body>
</html>

server.js

var http = require('http'), io = require('socket.io'),

server = http.createServer(function(req, res){ 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end('<h1>Hello world</h1>'); 
});
server.listen(8090);

var socket = io.listen(server); 
socket.on('connection', function(client){ 
    console.log('client connected');

    client.on('message', function(){ 
        console.log('message arrive');
        client.send('some message');
    });

    client.on('disconnect', function(){
        console.log('connection closed');
    });
});

关于我可能做错的任何想法?没有显示任何控制台消息。值得注意的是,当我使用 Firebug 查看 index.html 页面时,没有嵌入任何脚本,这很奇怪..不确定是什么原因造成的。

【问题讨论】:

    标签: node.js socket.io


    【解决方案1】:

    您没有在 index.html 文件中正确加载 socket.io 库。试试这个:

    <script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script> 
    

    【讨论】:

    • +1,比从远程主机获取脚本正确且更好的方法。
    【解决方案2】:

    您没有提供 socket.io.js(或 flash 文件)。

    我建议使用 CDN:

    &lt;script src="http://cdn.socket.io/stable/socket.io.js"&gt;&lt;/script&gt;

    或者使用express 提供socket.io.js 文件。

    编辑:

    err 实际上看起来更近了,您也没有提供 index.html 再次表达可以工作,但对于简单的例子:

    var fs = require('fs');
    var index = fs.readFileSync('index.html');
    //note the readFileSync is done only in the first tic
    .
    .
    .
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end(index); 
    

    【讨论】:

    • 使用 CDN 版本实际上存在一些问题.. 对我来说 websockets 不起作用.. 我建议坚持使用本地版本
    • 啊,就是这样!我最初使用的是 express,但回到 http 以隔离问题。我已经回去表达并开始使用 app.configure('development') 功能。感谢您的帮助!
    【解决方案3】:

    在客户端使用这个作为路径!

    <script type="text/javascript" src="/socket.io/socket.io.js"></script> 
    

    【讨论】:

      【解决方案4】:

      是的,并评论以下行:

      // server.listen(8090);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-20
        • 1970-01-01
        • 2011-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多