I am looking to write a data recorder that uses HTTP/2 to stream data from clients to the recorder, as well as retrieve data from a recorder via streams.
Looking at the JavaScript API for HTTP/2, it's not obvious to me how to keep a stream open and to exchange bidirectional traffic until some trigger event ends the recording.
Hence, I'm seeking examples (preferably JavaScript) of how to perform bidirectional exchanges for long lasting connections.
The following code snippets form the basis of what I am trying to achieve.
Server:
import http2 from 'http2'
import fs from 'fs'
// Private key and public certificate for access
const options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('public-cert.pem'),
};
// Creating and initializing server
const server = http2.createServer(options);
server.on('error', (error) => {
console.log('Error: ' + error);
});
server.on('stream', (stream, requestHeaders) => {
stream.respond({
':status': 200,
'content-type': 'text/plain'
});
stream.on('data', (data) => {
console.log('Received data: ' + data.toString());
stream.write(data); // echo received data back
});
stream.on('close', () => {
console.log('stream closed');
});
stream.on('end', () => {
console.log('stream end');
});
});
server.listen(8000);
Client:
I originally specified the Content_Length in the POST request, but this produced errors, when attempting to send more than one message to the server.
import http2 from 'http2'
let x = 0;
// Creating and initializing client
const client = http2.connect('http://localhost:8000');
console.log("Client connected");
const msg1 = 'message 1';
let req = client.request({
':method': 'POST',
':path': '/',
'Content-Type': 'text/plain',
});
req.on('response', (responseHeaders, flags) => {
console.log("status : " + responseHeaders[":status"]);
});
req.write(msg1);
req.on('data', (data) => {
console.log('Received: %s ', data.toString());
req.write("aaa" + x.toString());
x = x + 1;
if (x > 10) {
req.close();
}
});
req.on('end', () => {
client.close(() => {
console.log("client closed");
})
});
req.on('error', (error) => {
console.log(error);
})
The output on the server is:
Received data: message 1
Received data: aaa0
Received data: aaa1
Received data: aaa2
Received data: aaa3
Received data: aaa4
Received data: aaa5
Received data: aaa6
Received data: aaa7
Received data: aaa8
Received data: aaa9
Received data: aaa10
stream end
stream closed
The output on the client is:
Client connected
status : 200
Received: message 1
Received: aaa0
Received: aaa1
Received: aaa2
Received: aaa3
Received: aaa4
Received: aaa5
Received: aaa6
Received: aaa7
Received: aaa8
Received: aaa9
client closed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With