websocket
双向通信
性能高
WebSocket是前台的东西,是HTML5带的一种东西
只有前台有WebSocket这个东西
后台没有,后台有Socket
使用socket.io实现WebSocket
引入依赖
1  | {  | 
前台
1.html
1  | 
  | 
后台
server.js
1  | const http=require('http');  | 
原生WebSocket实现
前台
raw_client.html
1  | 
  | 
后台
建立连接
原始数据
1  | GET / HTTP/1.1  | 
分析原始数据
- 第一行删掉
 
1  | Host: localhost:8080  | 
- 舍弃第一行和最后两行
 
lines=lines.slice(1, lines.length-2);

- 每行数据用”: “切开
 
代码
raw_server.js
引入net模块
1  | const http=require('http');  | 
解析真正数据
真正数据

1  | 81 9c 11 2d f8 bd 数据.....  | 
帧结构
1  | 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7  | 
传递数据单位
1位(bit)
8位等于1字节(byte)
代码
raw_server2.js
1  | const http=require('http');  | 
总结
流程
引入net模块
握手
1  | 客户端:version:13、sec-websocket-key:xxxxx、sha1(key+mask)=>base64  | 
客户端
- onopen
 - onmessage
 - onclose
 
服务端
- net.createServer(sock=>{});
 - sock.once(‘data’, 握手);
 - sock.on(‘data’, 数据请求);
 - sock.on(‘end’);