Mallikarjuna
Mallikarjuna

Reputation: 401

Node - how send continuous HTTP responses back to client

I am working on the node js and it is very new to me. Here I have the following functionality, I am calling the Http request from the JS and waiting for the responses back from the Http response. Here I am getting the response correctly, but in me scenario I am working on the sensor device. So, I need to get the continuous responses from the HTTP. I am using the

msg.res.send(200, 'Thanks for the request ');

and it is sending back 'Thanks for the request' to the client. But if I use

msg.res.send(200, 'Thanks for the request ');
msg.res.send(200, 'Thanks for the request ');

like this continuously, first one working fine and getting error for second one like follows

Error: Can't set headers after they are sent.

Could please help me to solve this problem, because I need to get the continuous responses back from the HTTP to client.

Thanks in Advance

Upvotes: 1

Views: 3416

Answers (1)

Ralstan Vaz
Ralstan Vaz

Reputation: 76

Since Http is a stateless protocol the connection would end as soon as you send a response back.

The best way to achieve what you are looking for is opening up a tcp connection to the server. You can then keep sending data through this connection.

var net = require('net');

var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
    console.log('Connected');
    client.write('Thanks you');
    client.write('Another thank you');
});

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

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

If http is the only option you will have to wait till you get all the required data and then at once send it. via res.status(200).send('Thank you' + 'Another thank you')

Upvotes: 4

Related Questions