Node.js websocket服务器draft-ietf-hybi-thewebsocketprotocol-08

时间:2011-11-20 19:59:12

标签: javascript node.js websocket

我在我的项目中使用此代码:https://github.com/ncr/node.ws.js/blob/master/ws.js

使用Opera,Safari和FF它可以很好地工作,但是使用googlechrome它不起作用,因为chrome使用其他协议(draft-ietf-hybi-thewebsocketprotocol-08)

我无法设置socket.io,因此我必须修改此代码:https://github.com/ncr/node.ws.js/blob/master/ws.js

1 个答案:

答案 0 :(得分:0)

要发送握手,您需要按照定义实施算法:

// request is a string containing the handshake request

var match = /^Sec-WebSocket-Key: (.*)$/.exec(request); // parse request key

if(!match) {
    // not a valid request
}

var crypto = require("crypto"),
    hash   = crypto.createHash("sha1"),
    add    = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

hash.update(match[1] + add);

var key = hash.digest("base64"); // get response key

// build response
var response = "HTTP/1.1 101 Switching Protocols\r\n" +
               "Upgrade: websocket\r\n" +
               "Connection: Upgrade\r\n" +
               "Sec-WebSocket-Accept: " + key + "\r\n\r\n";

// send response now

有关发送和接收消息,请参阅this wiki question