webSocket双向通信
2019-06-28 本文已影响0人
简小园
优点
- 性能高
- 双向
- 自带跨域
对应的库
socket.io
- 简单、方便
- 兼容 IE5
- 自动数据解析
前台
<script src="http://localhost:8080/socket.io/socket.io.js" charset="utf-8"></script>
<script>
let sock=io.connect('ws://localhost:8080/');
//发送数据 sock.emit
//接收数据 sock.on
// 发送
sock.emit('aaa', 11, 3);
// 接收
sock.on('timer', time=>{
console.log(time);
});
</script>
后台
const http=require('http');
const io=require('socket.io');
//1.建立普通http
let server=http.createServer((req, res)=>{});
server.listen(8080);
//2.建立ws
let wsServer=io.listen(server);
wsServer.on('connection', sock=>{
// 发送数据 sock.emit('name', 数据)
// 接收数据 sock.on('name', function (数据){});
// 接收
sock.on('aaa', function (a, b){
console.log(a, b, a+b);
});
// 定时发送
setInterval(function (){
sock.emit('timer', new Date().getTime());
}, 1000);
});
原生webSocket
了解三次握手
前台
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script>
let ws=new WebSocket('ws://localhost:8080/');
ws.onopen=function (){
alert('连接已建立');
};
ws.onmessage=function (){};
ws.onclose=function (){};
ws.onerror=function (){};
</script>
</head>
<body></body>
</html>
后台
const net=require('net');
const crypto=require('crypto');
function parseHeader(str){
let arr=str.split('\r\n').filter(line=>line);
arr.shift();
let headers={};
arr.forEach(line=>{
let [name, value]=line.split(':');
name=name.replace(/^\s+|\s+$/g, '').toLowerCase();
value=value.replace(/^\s+|\s+$/g, '');
headers[name]=value;
});
return headers;
}
let server=net.createServer(sock=>{
sock.once('data', buffer=>{
let str=buffer.toString();
let headers=parseHeader(str);
if(headers['upgrade']!='websocket'){
console.log('no upgrade');
sock.end();
}else if(headers['sec-websocket-version']!='13'){
console.log('no 13');
sock.end();
}else{
let key=headers['sec-websocket-key'];
let uuid='258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
let hash=crypto.createHash('sha1');
hash.update(key+uuid);
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`);
}
});
sock.on('end', ()=>{
});
});
server.listen(8080);