websocket

作者: 秋天de童话 | 来源:发表于2019-01-17 22:46 被阅读4次

server.js

const http=require('http');
const net=require('net');         //TCP     原生Socket
const crypto=require('crypto');

/*
let server=http.createServer((req, res)=>{
  console.log('连接');
});
server.listen(8080);
*/

let server=net.createServer(sock=>{
  console.log('连接');

  //数据过来——握手只有一次
  sock.once('data', data=>{
    console.log('hand shake start...');

    let str=data.toString();
    let lines=str.split('\r\n');

    //舍弃第一行和最后两行
    lines=lines.slice(1, lines.length-2);

    //切开
    let headers={};
    lines.forEach(line=>{
      let [key, val]=line.split(': ');

      headers[key.toLowerCase()]=val;
    });

    //console.log(headers);

    if(headers['upgrade']!='websocket'){
      console.log('其他协议', headers['upgrade']);

      sock.end();
    }else if(headers['sec-websocket-version']!=13){
      console.log('版本不对', headers['sec-websocket-version']);

      sock.end();
    }else{
      let key=headers['sec-websocket-key'];
      let mask='258EAFA5-E914-47DA-95CA-C5AB0DC85B11';

      //sha1(key+mask)->base64=>client

      let hash=crypto.createHash('sha1');
      hash.update(key+mask);
      let key2=hash.digest('base64');

      sock.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${key2}\r\n\r\n`);

      console.log('hand shake end');

      //真正的数据
      sock.on('data', data=>{
        console.log('有数据');

        console.log(data);
      });
    }
  });

  //断开了
  sock.on('end', ()=>{
    console.log('客户端已断开');
  });
});
server.listen(8080);

client.jsp

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script>
    let sock=new WebSocket('ws://localhost:8080/');

    sock.emit=function (name, ...args){
      alert(JSON.stringify({name, data: [...args]}));
      sock.send(JSON.stringify({name, data: [...args]}));
    };

    //连上了
    sock.onopen=function (){
      alert('连接上了');


      sock.emit('msg', 12, 5);
    };

    //有数据
    sock.onmessage=function (){
      alert('有消息过来');
    };

    //断开了
    sock.onclose=function (){
      alert('断了');
    };
    </script>
  </head>
  <body>

  </body>
</html>

相关文章

网友评论

      本文标题:websocket

      本文链接:https://www.haomeiwen.com/subject/kenwdqtx.html