简体   繁体   中英

websocket handshake on node.js

I am trying to build a code that manage websocket connection with node.js

I am not finding a way to have the handshake being accept in chrome

Chrome return "WebSocket connection to 'ws://127.0.0.1:8888/' failed: Error during WebSocket handshake: Sec-WebSocket-Accept mismatch "

with this

<<>>>

var http=require("http");
var crypto=require("crypto");

var server=http.createServer(function(req,res){

res.writeHeads("200","content-type:text/plain");
res.end();  


    });

    server.on("upgrade",function(req,socket,head){

        for(var item in req.headers){
console.log(item);  
console.log(req.headers[item]); 
        }


var GUID="258EAFA5-E914-47DA-95CA-C5AB0DC85B11";    

var secKey=req.headers["sec-websocket-key"];


var sha=crypto.createHash("sha1");
secKey+=GUID;
secKey=sha.update(secKey).digest("base64");

var key64=new Buffer(secKey);
key64=key64.toString("base64");



console.log(key64);

var headersReturn='HTTP/1.1 101 Switching Protocols\r\n';
headersReturn+='Upgrade: websocket\r\n';
headersReturn+='Connection: Upgrade\r\n';
headersReturn+='Sec-WebSocket-Accept:'+key64+"\r\n\r\n";

var boo=socket.write(headersReturn);

console.log(headersReturn); 

socket.on("connect",function(){console.log("success");});
socket.on("data",function(data){
console.log(data);  
    });     

        });

        server.listen(8888,"127.0.0.1",function(){

console.log("server is on 8888");



            });

<<<>>>>

Hope someone would see what is missing.

The problem with the code is you are trying to base64 twice. No need to base64 the secKey.Its already in base64.

Comment the following lines.

var key64=new Buffer(secKey);
key64=key64.toString("base64");

Add this code after the above commented lines.

var key64 = secKey;

After the above modification the errors vanished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM