我正在嘗試在nodejs中編寫一個非常簡單的websocket服務器,並且遇到了一個問題。在瀏覽器中,WebSocket.onclose函數是唯一被觸發的函數(onopen,onmessage和onerror不是)。我已經測試過Chrome7和FireFox4。這裏是我的服務器代碼:NodeJS WebSocket握手無聲失敗?
var http = require('http'), net = require('net'), crypto = require('crypto'); var server = http.createServer(function (req, res) { console.log(req); }); server.on('connection', function (stream) { stream.setEncoding('utf8'); stream.setTimeout(0); stream.setNoDelay(true); stream.on('data', function (data) { var sec1_regex = /Sec-WebSocket-Key1:(.*)/g; var sec2_regex = /Sec-WebSocket-Key2:(.*)/g; var origin_regex = /Origin: (.*)/g; var protocol_regex = /Sec-WebSocket-Protocol: (.*)/g; console.log(stream); console.log("****Incoming****\r\n" + data); var key1 = sec1_regex.exec(data)[1]; var num1 = parseInt(key1.match(/\d/g).join(''))/(key1.match(/\s/g).length - 1); console.log("num1: " + num1); var key2 = sec2_regex.exec(data)[1]; var num2 = parseInt(key2.match(/\d/g).join(''))/(key2.match(/\s/g).length - 1); console.log("num2: " + num2); var lastbytes = data.slice(-8); var origin = origin_regex.exec(data)[1]; var md5 = crypto.createHash('md5'); md5.update(String.fromCharCode(num1 >> 24 & 0xFF, num1 >> 16 & 0xFF, num1 >> 8 & 0xFF, num1 & 0xFF)); md5.update(String.fromCharCode(num2 >> 24 & 0xFF, num2 >> 16 & 0xFF, num2 >> 8 & 0xFF, num2 & 0xFF)); md5.update(lastbytes); var response = "HTTP/1.1 101 WebSocket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Origin: " + origin + "\r\nSec-WebSocket-Location: ws://127.0.0.1:8124/\r\n" + md5.digest('binary'); stream.write(response, 'binary'); console.log("****Outgoing****\r\n" + response); }); }); server.listen(8124, '127.0.0.1');
而我的客戶端代碼:
function connect() { if (window.WebSocket) { try { ws = new WebSocket('ws://127.0.0.1:8124'); ws.onopen = function() { alert("open"); }; ws.onclose = function() { alert("close"); }; ws.onerror = function(err) { alert("err!"); }; ws.onmessage = function() { alert('message'); }; } catch (ex) { alert(ex); } } }
你真的應該使用'parseInt函數(...,10)'來確保你解析字符串作爲基地10號。否則,你可能會得到奇怪的結果:'parseInt(「070」)=== 56'。 – pimvdb 2011-09-16 17:48:29