[英]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.