我對Node.js的一些代碼,我一直在node.exe運行,看起來像這樣:JavaScript的WebSocket連接的readyState = 0與服務器的連接
// http://www.zhihua-lai.com/acm
// 09-Feb-2013
var sys = require('sys');
var net = require('net');
var sockets = [];
var svr = net.createServer(function(sock) {
sys.puts('Connected: ' + sock.remoteAddress + ':' + sock.remotePort);
sock.write('Hello ' + sock.remoteAddress + ':' + sock.remotePort + '\n');
sockets.push(sock);
sock.on('data', function(data) { // client writes message
if (data == 'exit\n') {
sys.puts('exit command received: ' + sock.remoteAddress + ':' + sock.remotePort + '\n');
sock.destroy();
var idx = sockets.indexOf(sock);
if (idx != -1) {
delete sockets[idx];
}
return;
}
var len = sockets.length;
for (var i = 0; i < len; i ++) { // broad cast
if (sockets[i] != sock) {
if (sockets[i]) {
sockets[i].write(sock.remoteAddress + ':' + sock.remotePort + ':' + data);
}
}
}
});
sock.on('end', function() { // client disconnects
sys.puts('Disconnected: ' + data + data.remoteAddress + ':' + data.remotePort + '\n');
var idx = sockets.indexOf(sock);
if (idx != -1) {
delete sockets[idx];
}
});
});
var svraddr = '127.0.0.1';
var svrport = 8080;
svr.listen(svrport, svraddr);
sys.puts('Server Created at ' + svraddr + ':' + svrport + '\n');
一旦我有服務器運行我可以打開兩個終端客戶端並使用NetCat或telnet。當我將信息輸入到任一客戶端窗口時,信息將廣播到兩個NetCat窗口。我遇到的麻煩是當我嘗試創建一個JavaScript連接到服務器。
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
<script type="text/javascript">
var connection = new WebSocket('ws://localhost:8080');
console.log(connection);
// When the connection is open, send some data to the server
connection.onopen = function() {
connection.send("a"); // Send the message 'Ping' to the server
console.log("send data...");
};
</script>
<body>
</body>
</html>
會發生什麼情況是連接的readyState爲0,表示Google Chromes JavaScript無法打開與服務器的連接。我確定Windows防火牆已關閉,以避免任何連接問題,並且服務器與NetCat正常工作。我想現在進一步使用Nodejs並獲取JavaScript來連接到服務器,但我不確定那將會發生什麼,或者需要更改哪些代碼。
在此先感謝...