【发布时间】: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