I have a working http2 server and client where I am sending a JSON data from client to server using POST method. As http2 in Node.js has duplex stream, I read the data from server stream using events 'data' and 'end'. Now I want to send the same data multiple times. But how do I differentiate new data from old data?
I want to do this using sleep ,because (correct me if I am wrong) when we send many many packets from clients to server it will eventually eat up all my CPU resource. Now how will the stream events in server behave when they don't receive data (I mean 'data' and 'end') , and how will I use them again to get data? Assume that when server receive data it stores it in a file.
Server:
const h2=require('http2');
const fs=require('fs');
const options={
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
//server begin
const server=h2.createSecureServer(options);
server.on('error', (err)=>{throw err});
server.on('stream', (stream, headers)=>{
stream.respond({':status': 200}) //giving out response headers
if(headers[':method']==='POST'){
let data=''
let i=0;
stream.on('data',(chunk)=>{
console.log(`iteration: ${++i}`)
data+=chunk
});
stream.on('end', ()=>{
// stream.close()
console.log('\n')
console.log(JSON.parse(data))
})
}else if(headers[':method']==='GET'){
stream.end('Hello from SMF')
}else{
//else condition
}
})
server.listen(3000, 'localhost');
//server end
Client:
const h2=require('http2');
const fs=require('fs');
const packet=require('./packet.json');
//client start
const client=h2.connect('https://localhost:3000',{ //establishing connection
ca: fs.readFileSync('cert.pem')
});
client.on('error', (err)=>{throw err})
const req=client.request({ //giving out a post request
':method': 'POST',
'content-type': 'application/json'
})
req.setEncoding('utf8');
req.on('error', (err)=>{throw err})
// req.write(JSON.stringify(packet))
req.end(JSON.stringify(packet), ()=>{ //writing the data to SMF
req.on('response', (headers)=>{ //getting the response headers
if(headers[':status']===200) console.log('success')
req.close() //closing client stream
client.close() //closing client session
})
})
//client end
JSON data:
{
"supi": "imsi-<IMSI>",
"pduSessionId": 235,
"dnn": "<DNN>",
"sNssai": {
"sst": 0
},
"servingNfId": "<AMF Identifier>",
"n1SmMsg": {
"contentId": "n1msg"
},
"anType": "3GPP_ACCESS",
"smContextStatusUri": "<URI>"
}
(I know that I have used secure server, you can just remove certificates from code and use createServer() instead).
I solved this using TimeInterval in javascript...
i=0;
let timer=setInterval(()=>{
i++;
req.write(JSON.stringify(packet)); //sending request packet
if(i==5){ //no of packets
req.end(()=>{
req.close();
client.close();
})
clearInterval(timer);
}
}, 10) //time interval
I was able to send multiple files using this