ExBuffer,NodeJs的TCP中的粘包、分包问题的解决方案!
推荐结合ByteBuffer来做通信协议!https://github.com/play175/ByteBuffer
var ExBuffer = require('./ExBuffer');
var exBuffer = new ExBuffer().uint32Head().littleEndian();
var exBuffer = new ExBuffer().ushortHead().bigEndian();
exBuffer.on('data',function(buffer){
console.log('>> receive data,length:'+buffer.length);
});
exBuffer.put(new Buffer([0,9]));
exBuffer.put(new Buffer([1,2,3,4,5,6,7]));
exBuffer.put(new Buffer([8,9]));
exBuffer.put(new Buffer([0,3,1,2,3,0,6,1,2,3,4,5,6]));
var exBuffer = new ExBuffer().uint32Head().bigEndian();
exBuffer.on('data',function(buffer){
console.log('>> receive data,length:'+buffer.length);
console.log(buffer);
});
var sbuf = new Buffer(4);
sbuf.writeUInt32BE(1024*1024*20,0);
exBuffer.put(sbuf);
exBuffer.put(new Buffer(1024*1024*20));
console.log('-----------------------use in socket------------------------');
var net = require('net');
var server = net.createServer(function(socket) {
console.log('client connected');
new Connection(socket);
});
server.listen(8124);
function Connection(socket) {
var exBuffer = new ExBuffer();
exBuffer.on('data',onReceivePackData);
socket.on('data', function(data) {
exBuffer.put(data);
});
function onReceivePackData(buffer){
console.log('>> server receive data,length:'+buffer.length);
console.log(buffer.toString());
var data = 'wellcom, I am server';
var len = Buffer.byteLength(data);
var headBuf = new Buffer(2);
headBuf.writeUInt16BE(len, 0)
socket.write(headBuf);
var bodyBuf = new Buffer(len);
bodyBuf.write(data);
socket.write(bodyBuf);
}
}
var exBuffer = new ExBuffer();
var client = net.connect(8124, function() {
var data = 'hello I am client';
var len = Buffer.byteLength(data);
var headBuf = new Buffer(2);
headBuf.writeUInt16BE(len, 0)
client.write(headBuf);
var bodyBuf = new Buffer(len);
bodyBuf.write(data);
client.write(bodyBuf);
});
client.on('data', function(data) {
exBuffer.put(data);
});
exBuffer.on('data', function(buffer) {
console.log('>> client receive data,length:'+buffer.length);
console.log(buffer.toString());
});
安装
npm install ExBuffer