Making net.Socket connection to remote port in a node API endpoint

1.4k views Asked by At

I've a ues case, where I need to connect to the remote socket and send incoming HTTP payload. Here is a sample code that I've written,

const net = require('net');
const express = require('express');
var backendConfig = require('./backend_config')
const app = express();
const port = 8080;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post('/', function(req, res){
     const backendName = "UBPS";
     var client = new net.Socket();

     client.connect(backendConfig[backendName]["port"], backendConfig[backendName]["url"], function() {
     console.log('Connected');
     var a = Buffer.from(req.body.isoMessage, 'hex');
     console.log(a)
     client.write(a);
});

client.on('data', function(data) {
    console.log('Received: ' + data);
    res.send(data);
    client.end(); // kill client after server's response
});

client.on('close', function() {
    console.log('Connection closed');
});
});


app.listen(port, function () {
    console.log('Example app listening on port 8080!');
 });

When I curl to the endpoint, I get a message that the socket is connected and data is written however, I don't receive a message of response received. One more point, the standalone nodejs code works just fine.

var client = new net.Socket();
client.connect(port, ip, function() {
    console.log('Connected');
    var a = Buffer.from("245463", 'hex');
    console.log(a)
    client.write(a);
});

client.on('data', function(data) {
     console.log('Received: ' + data);
     var b = Buffer.from(data,"str");
     console.log(b.toString());
     var a = Buffer.from(data, 'hex');
     console.log(a.toString());
     client.end(); // kill client after server's response
});

client.on('close', function() {
     console.log('Connection closed');
});

Can someone help me understand where I'm doing wrong?

I'm ok with any other solution as well. Essentially, I want to connect to a socket server from node server. No restriction on the libraries.

1

There are 1 answers

6
Algo7 On

You have to put your code:

var client = new net.Socket();
client.connect(port, ip, function() {
    console.log('Connected');
    var a = Buffer.from("245463", 'hex');
    console.log(a)
    client.write(a);

outside of the app.post('/', function(req, res){ ... route.

Otherwise, the connection will only be opened when and only when that route is hit. Furthermore, because the new net socket instance is created under the post route, it will be limited as a block scope variables and this not accessible from the other routes.