websocket handshake on node.js

左心房为你撑大大i 提交于 2020-01-03 20:04:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18098297/websocket-handshake-on-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!