繁体   English   中英

NodeJS和HTML5 Websockets无法协同工作

[英]NodeJS and HTML5 Websockets not working together

我在我的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)中测试过此脚本。

有没有人有什么建议?

谢谢!

您没有运行WebSocket服务器,而是运行HTTP服务器。 我写了一篇关于WebSockets和Node.js教程 ,尝试阅读它以获得更详细的解释。

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

我建议您查看socket.io ,它提供了一个通用的跨浏览器API,透明地使用浏览器支持的任何内容(包括websockets)。 官方服务器端实现在NodeJS中。 这个问题中有人建议。

由于协议级别存在严重的安全漏洞Firefox已在即将发布的预发行版中禁用了Websockets Opera已经宣布将在第11版中做同样的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM