mic*_*ael 3 javascript html5 websocket node.js
我在我的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 + '/');
Run Code Online (Sandbox Code Playgroud)
然后我跑...
node example.js
Run Code Online (Sandbox Code Playgroud)
...在一个终端,它给了我以下......
Server running at http://localhost:8080/
Run Code Online (Sandbox Code Playgroud)
我用以下代码创建了一个简单的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>
Run Code Online (Sandbox Code Playgroud)
但是当我浏览到页面时,我得不到任何反馈,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.