c语言编程笔录

首页 >   > 笔记大全

笔记大全

如何用Node手写WebSocket协议

更新时间:2023-09-11

WebSocket实例

var net=require('net'); 

net.createServer(function (socket) { 
    socket.on('data', function (data) { 
        var httpHeader=data.toString(); 
        var match=httpHeader.match(/Sec-WebSocket-Key: (.+)/); 
        var key=match[1]; 
        var magicString='258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; 
        var sha1=require('crypto').createHash('sha1'); 
        sha1.update(key + magicString); 
        var keyHash=sha1.digest('base64'); 
        var responseHeader='HTTP/1.1 101 Switching Protocols\r\n' + 
    'Upgrade: websocket\r\n' + 
    'Connection: Upgrade\r\n' + 
    'Sec-WebSocket-Accept: ' + keyHash + '\r\n' + 
    '\r\n'; 

    socket.write(responseHeader); 

    // 第一次握手成功后,服务器与客户端才建立了 TCP 连接
    socket.on('data', function (data) { 
        var end=0;
        var FIN=(data[0]>>7) & 0x1;
        var opcode=data[0] & 0xF;
        var len=data[1] & 0x7F;
        var text='';

        if (FIN && opcode===0x1) { // 0x1 为 text 类型
            text=data.slice(2, 2+len).toString();
            end=len + 2; 
        } 

        sum=0; 
        for (var i=0; i<4; i++) { 
            sum=sum + ((data[6]<<8*i)&(0xFF<<8*i)); 
        } 

        if (len < 126) { 
            maskStart=2; 
        } else if (len < 65536) { 
            maskStart=4; 
        } else { 
            maskStart=10; 
        } 

        var mask=new Buffer(4); 
        mask[0]=data[maskStart+0]; 
        mask[1]=data[maskStart+1]; 
        mask[2]=data[maskStart+2]; 
        mask[3]=data[maskStart+3]; 

        text=''; 
        var j=0; 
        for (var i=maskStart+4; i65535) { 
            outbuf[1]=0xFF; 
            outbuf=Buffer.concat([outbuf, new Buffer(8)]); 
        } else if (len>125) { 
            outbuf[1]=0xFE; 
            outbuf=Buffer.concat([outbuf, new Buffer(2)]); 
        } else { 
            outbuf[1]=len; 
            outbuf=Buffer.concat([outbuf, new Buffer(0)]); 
        } 
        return Buffer.concat([outbuf,responseBuffer]); 
        }); 
    }); 
}).listen(8080, "127.0.0.1");