简体   繁体   English

如何为Node.js“网络”创建伪造的服务器?

[英]How to create a fake server for Node.js “net”?

Background 背景

I have a use case where my application receives data from a machine every X seconds. 我有一个用例,其中我的应用程序每隔X秒从计算机接收一次数据。

This application connects to that machine via an IP address and a Port, using the net official library from Node.js. 此应用程序通过一个IP地址和端口连接到这台机器,使用net从Node.js的官方图书馆

const net = require("net");
const config = require("./config.json");

const client = new net.Socket();

client.connect(config.readerPort, config.readerIP, () => console.log("Connected"));

client.on("close", () => console.log("Connection closed"));

client.on("data", console.log);

Objective 目的

My objective here is to create a fake server that, just like the machine, allows my app to connect to it via an IP and a Port, and that emits events every X seconds as well. 我的目标是创建一个伪造的服务器,该伪造的服务器就像机器一样,允许我的应用通过IP和端口连接到该服务器,并且每隔X秒发出一次事件。

To simulate this I have created a small app that prints 0 every 5 seconds: 为了模拟这一点,我创建了一个小应用程序,每5秒打印一次0:

setTimeout(() => {
    console.log(0);
}, 5000);

My objective is to, instead of printing to the console, to bind the small app to an IP and a port (localhost) and then make my app read from it. 我的目标是(而不是打印到控制台)将小型应用程序绑定到IP和端口(本地主机),然后从中读取我的应用程序。

Question

Using the net library from Node.js (or any other), how do change my fake server from printing to the console to sending that information to the localhost IP and a port? 使用Node.js(或其他任何网站)中的net库,如何将我的假服务器从打印到控制台更改为将信息发送到本地IP和端口?

Solution

After much searching, I actually found a way to do this without any external libraries besides net . 经过大量搜索,我实际上找到了一种方法,除了net之外,没有任何外部库。

The result I came to is a variation of this: 我得出的结果是这种变化:

const net = require('net');

const HOST = '127.0.0.1';
const PORT = 6969;

net.createServer( sock => {

    console.log(`CONNECTED: ${sock.remoteAddress}:${ sock.remotePort}`);

    sock.on('close',() => console.log("CLOSED"));

    setTimeout(() => {
        sock.write("Hello WOrld\r\n");
    }, 10000);        

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

Then my client machine will happily pick after it. 然后我的客户端计算机会很乐意选择它。

You can find the original tutorial/source here: 您可以在此处找到原始教程/源:

Tips 提示

It is important to watch out with line terminations. 注意线路终端很重要。 According to node.js socket.write() not work on if condition if you don't add termination characters like \\r\\n , some clients won't accept them. 根据node.js,如果不添加\\r\\n类的终止字符,则socket.write()无法在if条件下工作 ,某些客户端不会接受它们。

Another important consideration may be that you need to force the output put of write to be immediate. 另一个重要的考虑因素可能是您需要强制输出write输出立即生效。 Read more at node.js socket.write() not work on if condition . node.js上阅读更多内容socket.write()在if condition上不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM