Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在 Node.js 中检测端口 port 是否被占用 #24

Open
AlexZ33 opened this issue Oct 29, 2019 · 0 comments
Open

在 Node.js 中检测端口 port 是否被占用 #24

AlexZ33 opened this issue Oct 29, 2019 · 0 comments

Comments

@AlexZ33
Copy link
Member

AlexZ33 commented Oct 29, 2019

    var calledOnce = false

    var timeoutRef = setTimeout(function () {
        calledOnce = true
        callback(false,port)
    }, 2000)

    timeoutRef.unref()

    var connected = false

    server.on('listening', function() {
        clearTimeout(timeoutRef)

        if (server)
            server.close()

        if (!calledOnce) {
            calledOnce = true
            callback(true,port)
        }
    })

    server.on('error', function(err) {
        clearTimeout(timeoutRef)

        var result = true
        if (err.code === 'EADDRINUSE')
            result = false

        if (!calledOnce) {
            calledOnce = true
            callback(result,port)
        }
    })
}

function server(_port){
    var pt = _port || __port;
    probe(pt,function(bl,_pt){
        // 端口被占用 bl 返回false
        // _pt:传入的端口号
        if(bl === true){
            // ssr(_pt)
            server = http.createServer(connListener);
            server = server.listen(parseInt(_pt, 10));
            console.log("\n  Static file server running at" + "\n\n=> http://localhost:" + _pt + '\n');
        }else{
            server(_pt+1)
        }
    })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant