UDP server
UDP 收到的數(shù)據(jù)是有邊界的, 可以確定收到的數(shù)據(jù)是發(fā)送端發(fā)出來的一個完整包.
const dgram = require('dgram');
const events = require('events');
const ip = require('internal-ip');
module.exports = class UDPServer extends events.EventEmitter {
constructor(port) {
super();
this.port = port;
this.server = dgram.createSocket('udp4');
this.server.on('error', err => {
console.log(`UDP 服務(wù)異常: ${err.stack}`);
this.server.close();
});
this.server.on('listening', async () => {
var host = await ip.v4();
console.log(`UDP 服務(wù)監(jiān)聽 ${host}:${this.port}`);
})
this.server.on('message', (msg, addr) => {
console.log(`UDP 服務(wù)收到數(shù)據(jù)長度: ${msg.length}`);
})
this.server.bind(this.port);
}
}
TCP server
TCP 收到的數(shù)據(jù)是流式的, 需要通過讀取固定字節(jié)頭的方式來解析數(shù)據(jù)包的邊界.
const net = require('net');
const events = require('events');
const ip = require('internal-ip');
module.exports = class TCPServer extends events.EventEmitter {
constructor(port) {
super();
this.port = port;
this.server = net.createServer();
this.server.on('listening', async () => {
var host = await ip.v4();
console.log(`TCP 服務(wù)監(jiān)聽 ${host}:${this.port}`);
})
this.server.on('connection', socket => {
console.log(`TCP server has a new connection`);
socket.on('error', e => {
console.log(`connect error: ${e.stack}`);
})
socket.on('end', () => {
console.log('connect end');
})
})
this.server.on('close', () => {
console.log('TCP server closed');
})
this.server.listen(this.port);
}
}