美文网首页
NodeJS socket server 示例

NodeJS socket server 示例

作者: penggy | 来源:发表于2018-04-29 14:38 被阅读0次

    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 示例

          本文链接:https://www.haomeiwen.com/subject/rglroxtx.html