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.