nodejs,net模块
单工
半双工的通信通道搭建
发送,然后登台接收,然后再发送
socket 套接字通信
交换机通信
web通信技术 https://zhuanlan.zhihu.com/p/21573180
轮询,每个一秒钟请求一次服务器,例如 定时器
长轮询
全双工通信的关键
- 在于应用层协议,需要有标记包段的信号
- 处理一下情况,需要有标记包长的字段
- 粘包
- 不完整包
- 错误处理
server
const net = require('net');
const server = net.createServer((socket) => {
socket.on('data', function(buffer) {
console.log(buffer);
const seqBuffer = buffer.slice(0, 2);
const lessonid = buffer.readInt32BE(2);
setTimeout(()=> {
// console.log(data[lessonid])
const buffer = Buffer.concat([
seqBuffer,
Buffer.from(data[lessonid])
])
socket.write(
buffer
);
}, 10 + Math.random() * 1000)
})
});
server.listen(4000);
const data = {
136797: "01 | 课程介绍",
136798: "02 | 内容综述",
136799: "03 | Node.js是什么?",
136800: "04 | Node.js可以用来做什么?",
136801: "05 | 课程实战项目介绍",
136803: "06 | 什么是技术预研?",
136804: "07 | Node.js开发环境安装",
136806: "08 | 第一个Node.js程序:石头剪刀布游戏",
136807: "09 | 模块:CommonJS规范",
136808: "10 | 模块:使用模块规范改造石头剪刀布游戏",
136809: "11 | 模块:npm",
141994: "12 | 模块:Node.js内置模块",
143517: "13 | 异步:非阻塞I/O",
143557: "14 | 异步:异步编程之callback",
143564: "15 | 异步:事件循环",
143644: "16 | 异步:异步编程之Promise",
146470: "17 | 异步:异步编程之async/await",
146569: "18 | HTTP:什么是HTTP服务器?",
146582: "19 | HTTP:简单实现一个HTTP服务器"
}
client
const net = require('net');
const socket = new net.Socket({});
socket.connect({
host: '127.0.0.1',
port: 4000
});
const lessonids = [
"136797",
"136798",
"136799",
"136800",
"136801",
"136803",
"136804",
"136806",
"136807",
"136808",
"136809",
"141994",
"143517",
"143557",
"143564",
"143644",
"146470",
"146569",
"146582"
]
let id = Math.floor(Math.random() * lessonids.length);
socket.on('data', (buffer) => {
const seqBuffer = buffer.slice(0, 2);
const titleBuffer = buffer.slice(2);
console.log(seqBuffer.readInt16BE(), titleBuffer.toString())
})
let seq = 0;
function encode(index) {
buffer = Buffer.alloc(6);
buffer.writeInt16BE(seq)
buffer.writeInt32BE(
lessonids[index], 2
);
console.log(seq, lessonids[index]);
seq++;
return buffer;
}
for (let k = 0; k < 100; k++) {
id = Math.floor(Math.random() * lessonids.length);
socket.write(encode(id));
}