NodeJS WebSocket握手无声失败?

时间:2010-09-03 05:09:50

标签: node.js websocket

我正在尝试在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);
    }
   }
  }
 

2 个答案:

答案 0 :(得分:2)

确定这里有一些问题,只有onclose句柄被触发的原因是因为浏览器没有收到有效的握手,因此终止了连接。

  1. 您始终发送ws://127.0.0.1:8124/作为位置,该位置应完全匹配浏览器在请求中发送的内容,在这种情况下,它很可能localhost:8124,因此您应该返回{{1}在这种情况下。

  2. 您在回复标题后错过了另一个ws://localhost:8124/,因此您实际上并未发送任何正文。

  3. 您的哈希值计算似乎有问题,我仍然想弄清楚虽然

  4. 对于一个工作(并且非常小)的实现,请参见此处:
    http://github.com/BonsaiDen/NodeGame-Shooter/blob/master/server/ws.js

答案 1 :(得分:1)

您可以收听http服务器的升级事件。

它喜欢:

httpserver.onupgrade = function(request, socket) {
var key = request.headers['sec-websocket-key'];
key = require('crypto').createHash('sha1').update(key+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest('base64');

var sResponse = "HTTP/1.1 101 Switching Protocols\r\n" +
    "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" +
    "Sec-WebSocket-Accept: " + key + "\r\n\r\n";
    socket.write(sResponse,'ascii');

//...
}