NodeJS和HTML5 Websockets不能一起工作

3
我已在我的Ubuntu机器上安装了NodeJS,并创建了以下脚本....
var host = 'localhost'
var port = '8080'
var net = require('net');

net.createServer(function (socket) {
    socket.write("Echo server\r\n");
    socket.on("data", function (data) {
        socket.write(data);
    });
}).listen(port, host);

console.log('Server running at http://' + host + ':' + port + '/');

我随后运行...
node example.js

在终端中,我得到了以下结果...

Server running at http://localhost:8080/

我用以下代码创建了一个简单的HTML页面...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
    <head>
      <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'></script>
      <script>
        $(document).ready(function(){
            if(!("WebSocket" in window)) {
                alert("Sorry, the build of your browser does not support WebSockets.");
                return;
            }

            ws = new WebSocket("ws://localhost:8080/");

            ws.onclose = function() {
                alert("socket closed");
            };
            ws.onopen = function() {
                alert("socked opened");
            };
            ws.onmessage = function() {
                alert("message received");
            };

            $( 'button' ).click( function() {
                ws.send( "testing" );
            });

            setInterval( function() {
                $( 'p.readyState' ).text( ws.readyState );
            }, 1000 );
        });
      </script>
    </head>
    <body>
        <button type="button">Click Me!</button>
        <p class="readyState"></p>
    </body>
</html>

但是当我浏览到该页面时,没有任何反馈,而且readyState始终为0。如果我在页面仍然打开的情况下停止服务器,我会收到套接字关闭警报。
我已经在Chrome(8.0.552.215),Firefox 4(Beta 7)和Opera 11(Beta)中测试了这个脚本。
有人有什么建议吗?
谢谢!
2个回答

7
你没有运行WebSocket服务器,而是运行HTTP服务器。我写了一篇关于WebSockets和Node.js的教程,建议阅读以获得更详细的解释。
你需要将连接升级为WebSocket连接,因为WS连接最初使用标准的HTTP请求。请使用Node的WebSocket服务器实现创建服务器,而不是使用net

3
我建议您查看socket.io,它提供了一个通用的跨浏览器API,透明地使用浏览器支持的任何内容(包括WebSockets)。官方服务器端实现在NodeJS中。这是在this question中提出的建议。 Firefox已经禁用了Websockets在即将发布的版本中,因为协议级别存在严重的安全漏洞。Opera在11版本中也宣布要这样做。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接