简体   繁体   中英

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.

This application connects to that machine via an IP address and a Port, using the net official library from 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.

To simulate this I have created a small app that prints 0 every 5 seconds:

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.

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?

Solution

After much searching, I actually found a way to do this without any external libraries besides 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.

Another important consideration may be that you need to force the output put of write to be immediate. Read more at node.js socket.write() not work on if condition .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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