【问题标题】:Node.js websocket server draft-ietf-hybi-thewebsocketprotocol-08Node.js websocket 服务器 Draft-ietf-hybi-thewebsocketprotocol-08
【发布时间】:2011-11-21 04:05:22
【问题描述】:

我在我的项目中使用此代码: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

【问题讨论】:

    标签: javascript node.js websocket


    【解决方案1】:

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

    // 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

    【讨论】:

    • handshake函数中,以data为请求字符串,使用socket.write写响应。
    猜你喜欢
    • 2011-09-22
    • 2011-10-26
    • 2011-08-13
    • 2011-12-15
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 2016-08-18
    • 2014-02-13
    相关资源
    最近更新 更多