更新时间:2023-01-17 21:51:11
使用 net.connect():
var net = require('net');var client = net.connect({端口: 8124},function() {//'连接' 监听器console.log('客户端连接');客户端端();});
Node.JS 文档 net
模块>
Summary: How can I use Node.js to see whether something is listening on a given port?
Details:
I am writing tests for an HTTP-based application in Node.
I've extended Node's http.Server
with util.inherits
, and in the resulting "class" wrap the standard .listen()
functionality in a method of my own called .start()
. This method performs some setup (e.g. connects to MongoDB) and then calls http.Server.listen(port, cb)
when everything is good to go.
My problem: I'd like to write a test that calls .start()
and then checks that the server is, indeed, listening on the specified port. I would like to do this without sending an HTTP request for the server to field. I just want to test that the server is listening.
Unfortunately, I am not familiar with TCP, but given my experience with port scanning and netstat
and things of that nature, I have the impression that something in Node's net package will let me do this. Is this possible?
Use net.connect():
var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('client connected');
client.end();
});
Node.JS documentation on net
module