我试图在 nodejs 中编写一个非常简单的 websocket 服务器,但我遇到了一个问题。在浏览器上,WebSocket.onclose 函数是唯一被触发的函数(onopen、onmessage 和 onerror 不是)。我已经在 Chrome7 和 FireFox4 中测试过。这是我的服务器代码:
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); } } }
最佳答案
好的,这里有一些问题,只有 onclose
句柄被触发的原因是因为浏览器没有收到有效的握手,因此终止了连接。
您始终发送
ws://127.0.0.1:8124/
作为位置,该位置应与浏览器在请求中发送的任何内容完全匹配,在这种情况下很可能localhost:8124
所以在这种情况下你应该返回ws://localhost:8124/
。您在响应 header 后缺少另一个
\r\n
,因此您实际上没有发送任何正文。你计算的hash值好像有问题,我还在想办法
有关工作(且非常小)的实现,请参见此处:
http://github.com/BonsaiDen/NodeGame-Shooter/blob/master/server/ws.js
关于node.js - NodeJS WebSocket 握手静默失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3633196/