本示列使用typescript编写 2017-10-17日更新 修复多网卡获取IP问题。
功能调用 getIdlePort(callback: (port: number, ip?: string) => void) 在回调中获得本机空闲端口
及IP地址,IP地址是数组类型。自己打印出来需要使用哪个ip地址自行配置吧。一般多网卡会有多个IP地址。
简要说明下本机IP地址是随时可以获取的,空闲服务端口号获取步骤如下:利用net本身,启动获取空闲的端
口,在 listenListeningHandle监听中获取空闲端口号 、listenCloseHandle监听中释放检测到的空闲端
口。如没释放直接使用,也只能呵呵了

最后更新时间:2018-5-29 新增linux系统
 type Platform = 'aix'
        | 'android'
        | 'darwin'
        | 'freebsd'
        | 'linux'
        | 'openbsd'
        | 'sunos'
        | 'win32'
        | 'cygwin';
系统类型,自己改源码吧。只有win32系统
其中typescrip 可以生成任意版本的JS代码 如ES5 .ES6等等
获取服务器 ip地址及端口号

import { BaseNetServer } from "../common/BaseNetServer";
import * as net from "net";
import { ServerEvent, SocketEvent } from '../Enum/SocketEvent';
import * as os from "os";
/**
 * 获取服务器 ip地址及端口号
 * 
 * @export
 * @class ServerPort
 */
export class ServerPort {
    public _server: net.Server = net.createServer();
    public _NetServer: BaseNetServer = new BaseNetServer(this._server);
    protected _callback?: (port: number, ip?: string[]) => void;
    protected _port: number;
    protected _ip: string[] | undefined;
    /**
     * 获取空闲端口号及IP地址。
     * 
     * @param {(port: Number, ip?: string) => void} callback 
     * @memberof ServerPort
     */
    public getIdlePort(callback: (port: number, ip?: string[]) => void) {
        this._callback = callback;
        this._server.addListener(ServerEvent.LISTENING, this.listenListeningHandle.bind(this));
        this._NetServer.startListener(0);

    }
    /**
     * 获取IP地址
     * 
     * @returns 
     * @memberof ServerPort
     */
    public getIp() {
        var IPv4: Array<string> = new Array;
        if (process.platform === 'linux') {
            for (let item in os.networkInterfaces()) {               
                let list = os.networkInterfaces()[item];
                for (let i = 0; i < list.length; i++) {
                    if (list[i].family == 'IPv4') {
                        IPv4.push(list[i].address);
                    }
                }
            }
        }else if (process.platform === 'darwin') {//os系统
            for (let i = 0; i < os.networkInterfaces().en0.length; i++) {
                if (os.networkInterfaces().en0[i].family == 'IPv4') {
                    IPv4.push(os.networkInterfaces().en0[i].address);
                }
            }
        } else if (process.platform === 'win32') {//win系统
            for (let item in os.networkInterfaces()) {
                let list = os.networkInterfaces()[item];
                for (let i = 0; i < list.length; i++) {
                    if (list[i].family == 'IPv4') {
                        IPv4.push(list[i].address);
                    }
                }
            }

        }
        //console.log(IPv4);
        return IPv4;
    }
    /**
     * Listening
     * 
     * @protected
     * @memberof BaseServer
     */
    protected listenListeningHandle(): void {
        if (this._callback) {
            this._port = this._server.address().port;
            this._ip = this.getIp();
            this._NetServer._server.close(this.listenCloseHandle.bind(this));
        }
    }

    /**
     * 关闭
     * 
     * @protected
     * @memberof ServerPort
     */
    protected listenCloseHandle(): void {
        if (this._callback) {
            this._callback(this._port, this._ip);
        }
        this._callback = undefined;
        console.log("Server关闭!");
    }
}

 
 
 
 
 
net简单封装
import * as net from 'net';
import { ServerEvent, SocketEvent } from '../Enum/SocketEvent';

/**
 * net.Server简单封装
 * 
 * @export
 * @class BaseServer
 */
export class BaseNetServer {
    protected _server: net.Server;// = net.createServer();
    constructor(server: net.Server) {
        this._server = server;
    }

    /**
     * 启动监听
     * 
     * @memberof BaseServer
     */
    public startListener(port: number) {
        this._server.addListener(ServerEvent.CONNECTION, this.listenConnectionHandle.bind(this));
        this._server.addListener(ServerEvent.CLOSE, this.listenCloseHandle.bind(this));
        this._server.addListener(ServerEvent.ERROR, this.listenErrorHandle.bind(this));
        this._server.addListener(ServerEvent.LISTENING, this.listenListeningHandle.bind(this));
        this._server.listen(port);
    }

    /**
     * connection连接监听
     * 
     * @protected
     * @memberof BaseServer
     */
    protected listenConnectionHandle(socket: net.Socket): void {
        //console.log("BaseServer connection 连接成功!base!");
    }

    /**
     * 
     * 
     * @protected
     * @param {Error} error 
     * @memberof BaseServer
     */
    protected listenErrorHandle(error: Error): void {
        console.log("BaseServer error:::::::" + error);
        throw error;
    }

    /**
     * Listening
     * 
     * @protected
     * @memberof BaseServer
     */
    protected listenListeningHandle(): void {
        //var port = this._server.address().port;
        //console.log(port);
        //console.log("Listening!");
    }

    /**
     * close连接关闭监听
     * 
     * @protected
     * @memberof BaseServer
     */
    protected listenCloseHandle(): void {
        //console.log("Server关闭!");
    }
}



/**
 * net.socket简单封装
 * 
 * @export
 * @class BaseSocket
 */
export class BaseSocket {
    protected _socket: net.Socket;
    constructor(socket: net.Socket) {
        this._socket = socket;
    }
    /**
     * 启动监听
     * 
     * @memberof BaseSocket
     */
    public startListener() {
        this._socket.addListener(SocketEvent.DATA, this.listenDataHandle.bind(this));
        this._socket.addListener(SocketEvent.CLOSE, this.listenCloseHandle.bind(this));
        this._socket.addListener(SocketEvent.ERROR, this.listenErrorHandle.bind(this));
    }
    /**
     * 接收客户端数据监听
     * 
     * @protected
     * @param {Buffer} data 
     * @memberof BaseSocket
     */
    protected listenDataHandle(data: Buffer): void {
        //console.log('BaseSocket 接收到的数据:', data.toString());
    }
    /**
     * error监听
     * 
     * @protected
     * @param {Error} error 
     * @memberof BaseSocket
     */
    protected listenErrorHandle(error: Error): void {
        console.log("BaseSocket error:" + error);
        throw error;
    }
    /**
     * 关闭监听
     * 
     * @protected
     * @memberof BaseSocket
     */
    protected listenCloseHandle(): void {
        //console.log("BaseSocket socket连接关闭!");
    }
    /**
     * socket end sockect关闭连接
     * 
     * @memberof BaseSocket
     */
    public socketEndHandle(): void {
        try {
            this._socket.end();
        } catch (error) {
            console.log("BaseSocket sockect关闭连接:" + error);
        }
    }

}
//}


enum

/**
 * net.Socket 的监听枚举
 * 
 * @export
 * @enum {number}
 */
export enum SocketEvent {
    CLOSE = "close",
    CONNECT = "connect",
    DATA = "data",
    DRAIN = "drain",
    END = "end",
    ERROR = "error",
    LOOKUP = "lookup",
    TIMEOUT = "timeout"
}
/**
 * net.ServerEvent 的监听枚举
 * 
 * @export
 * @enum {number}
 */
export enum ServerEvent{
    CLOSE ="close",
    CONNECTION="connection",
    ERROR="error",
    LISTENING="listening"
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐