protocol-buffers
https://www.npmjs.com/package/protocol-buffers
buffer
http://nodejs.cn/api/buffer.html#buffer_buf_writebigint64be_value_offset
tcp之单工通信
client和server之间,只能是单向的一方向另一方发送数据。
// client.js
const net = require('net');
const socket = new net.Socket();
socket.connect({port:2000});
process.stdin.on('data',e=>{
socket.write(Buffer.from([1,2,3]));
})
//server.js
const net = require('net');
net.createServer((socket) => {
socket.on('data',data=>{
console.log('server,',data,data.toString());
})
}).listen(2000,()=>{
console.log('server is running')
})
tcp之半双工通信
client和server,有来有往,如client发送一条消息,收到server响应后,才能发送下一条消息。
//client.js
const net = require('net');
const socket = new net.Socket();
socket.connect({port:2000});
let count = 0;
socket.write(Buffer.from(level()+''));
socket.on('data',data=>{
console.log('client,',data,data.toString());
count++;
if(count<10){
socket.write(Buffer.from(level()+''));
}
})
function level(){return Math.floor(Math.random()*(6-1+1))+1};
//server.js
const net = require('net');
net.createServer((socket) => {
socket.on('data',data=>{
console.log('server,',data,data.toString());
if(data){
socket.write('response');
}
})
}).listen(2000,()=>{
console.log('server is running')
})
tcp之全双工通信
client不停的发送请求,不需等到结果就可以发送下一个请求(需要有一个标识,来匹配请求和响应)
在一秒之内,server随机时间返回数据,来混淆数据包的顺序
//client.js
const net = require('net');
const socket = new net.Socket();
socket.connect({port:2000});
function send(num){
const buf = Buffer.allocUnsafe(2);
buf.write(num+'', 0); //请求标识
buf.write(level()+'', 1); //发送的消息
socket.write(buf);
}
socket.on('data',data=>{
console.log('client,',data.slice(1).toString(),data.slice(0,1).toString());
})
for(let i=0;i<10;i++){
setTimeout(()=>{
send(i);
},i*2*100)
}
function level(){return Math.floor(Math.random()*(6-1+1))+1};
//server.js
const net = require('net');
net.createServer((socket) => {
socket.on('data',data=>{
console.log('server,',data.slice(1).toString(),data.slice(0,1).toString());
if(data){
socket.write('response');
setTimeout(()=>{
const buf = Buffer.allocUnsafe(4);
buf.write(data.slice(0,1).toString(),0);
buf.write(obj[data.slice(1).toString()]||"",1);
socket.write(buf);
},10+Math.random()*1000)
}
})
}).listen(2000,()=>{
console.log('server is running')
})
const obj = {
0:'000',
1:'111',
2:'222',
3:'333',
4:'444',
5:'555',
6:'666',
7:'777',
8:'888',
9:'999'
}
网友评论