如何使用 Node.js 测试服务是否正在侦听 TCP? [英] How can I test that a service is listening on TCP with Node.js?

查看:31
本文介绍了如何使用 Node.js 测试服务是否正在侦听 TCP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总结:如何使用 Node.js 查看某个端口是否正在侦听某些内容?

详情:

我正在 Node.js 中为基于 HTTP 的应用程序编写测试.

我用 util.inherits 扩展了 Node 的 http.Server,并在生成的类"中包装了标准的 .listen() 我自己称为 .start() 的方法中的功能.此方法执行一些设置(例如连接到 MongoDB),然后在一切顺利时调用 http.Server.listen(port, cb).

我的问题:我想编写一个调用 .start() 的测试,然后检查服务器是否确实在监听指定的端口.我想在不向服务器发送 HTTP 请求的情况下执行此操作.我只想测试服务器是否正在侦听.

不幸的是,我对 TCP 并不熟悉,但鉴于我在端口扫描和 netstat 和类似事物方面的经验,我的印象是 something 在 Node 的<一个 href="http://nodejs.org/api/net.html" rel="nofollow">net 包会让我这样做.这可能吗?

解决方案

使用 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

这篇关于如何使用 Node.js 测试服务是否正在侦听 TCP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆