Node. js is a simple example of checking whether a port is occupied. node. jsport

Source: Internet
Author: User

Node. js is a simple example of checking whether a port is occupied. node. jsport

Preface

In network technology, a Port has two meanings: one is a physical Port, for example, ADSL Modem, Hub, switch, router is used to connect other network equipment interface, such as RJ-45 port, SC port and so on. The second is the logical port, which generally refers to the port in the TCP/IP protocol. The port number ranges from 0 to 65535, for example, used to browse Web Services. The purpose of this article is to solve the problem of port occupation when multiple services of the ssr tool are involved. We will share with you the code snippet of this study. If you need it, you can refer to it for reference.

Sample Code

// Check whether the port is occupied by function probe (port, callback) {var server = net. createServer (). listen (port) var calledOnce = false var timeoutRef = setTimeout (function () {calledOnce = true callback (false, port)}, 2000) timeoutRef. unref () var connected = false server. on ('listenering', 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) {// port occupied bl returns false // _ pt: input port number if (bl = true) {// ssr (_ pt) server = http. createServer (connListener); server = server. listen (parseInt (_ pt, 10); console. log ("\ n Static file server running at" + "\ n => http: // localhost:" + _ pt + '\ n ');} else {server (_ pt + 1 )}})}

Summary

The above is all about this article. I hope to help you in your study or work. If you have any questions, please leave a message.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.