NodeJS socket server 示例

UDP server

UDP 收到的数据是有边界的, 可以确定收到的数据是发送端发出来的一个完整包.

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 服务异常: ${err.stack}`);
            this.server.close();
        });
        this.server.on('listening', async () => {
            var host = await ip.v4();
            console.log(`UDP 服务监听 ${host}:${this.port}`);
        })
        this.server.on('message', (msg, addr) => {
            console.log(`UDP 服务收到数据长度: ${msg.length}`);
        })
        this.server.bind(this.port);
    }
}

TCP server

TCP 收到的数据是流式的, 需要通过读取固定字节头的方式来解析数据包的边界.

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 服务监听 ${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);
    }
}

你可能感兴趣的:(NodeJS socket server 示例)