A simple example of whether the Node.js detection port (port) is occupied _node.js

Source: Internet
Author: User

Objective

In Network technology, ports (port) generally have two meanings: first, the physical port, for example, ADSL Modem, hubs, switches, routers to connect other network devices, such as RJ-45 Port, SC port and so on. The second is the logical port, generally refers to the TCP/IP protocol port, the range of port number from 0 to 65535, such as for browsing Web services. The purpose of this article is to solve the SSR tool when a number of services to the port is occupied, the following to share the study of the Code snippets, there is a need for reference.

Sample code

Detect if port is occupied function probe (port, callback) {var server = Net.createserver (). Listen (port) var calledonce = False var timeoutref = settimeout (function () {Calledonce = True callback (False,port)}, Watts) timeoutref.unre F () var connected = False Server.on (' Listening ', function () {cleartimeout (TIMEOUTREF) if (server) SE Rver.close () if (!calledonce) {calledonce = True callback (True,port)}) Server.on (' Error ', Fu

    Nction (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: Incoming port number if (bl = = true) {//SSR (_PT) Server =
      Http.createserver (Connlistener);
      Server = Server.listen (parseint (_pt, 10)); Console.log ("\ n Static File serverRunning at "+" \n\n=> http://localhost: "+ _pt + ' \ n '); }else{Server (_PT+1)}})}

Summarize

The above is the entire content of this article, I hope to be able to learn or work to bring certain help, if you have questions you can message exchange.

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.