【问题标题】:NodeJS and HTML5 Websockets not working togetherNodeJS 和 HTML5 Websockets 不能一起工作
【发布时间】:2011-05-22 06:38:34
【问题描述】:

我已经在我的 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) 中测试了这个脚本。

有人有什么建议吗?

谢谢!

【问题讨论】:

    标签: javascript html node.js websocket


    【解决方案1】:

    您运行的不是 WebSocket 服务器,而是 HTTP 服务器。我写了一个tutorial on WebSockets and Node.js,尝试阅读它以获得更详细的解释。

    您需要将连接提升为 WebSocket 连接,因为 WS 连接最初使用标准 HTTP 请求。围绕Node's WebSocket Server 实现而不是net 创建一个服务器。

    【讨论】:

      【解决方案2】:

      我建议你看看socket.io,它提供了一个通用的跨浏览器 API,透明地使用浏览器支持的任何东西(包括 websockets)。官方的服务器端实现在 NodeJS 中。建议在this question

      Firefox has disabled Websockets 在即将发布的预发布中,因为在协议级别上有一个严重的security vulnerability。 Opera 已宣布在版本 11 中执行相同的操作。

      【讨论】:

        猜你喜欢
        • 2014-09-24
        • 1970-01-01
        • 2014-01-07
        • 2019-08-17
        • 2016-11-23
        • 2019-02-18
        • 2015-05-16
        • 2017-10-14
        • 2012-06-01
        相关资源
        最近更新 更多