i need your help... i am new to TCP.. I had implemented TCP server and client... tcp server write data when connection is established and wait for kernal buffer getting empty then i emit end event from TCPserver and same as client received data from server in end event...
TCP server.js
const TCPserver = net.createServer().listen(4040);
var recvData='';
TCPserver.on('connection',(TCPclient)=>{
TCPclient.setKeepAlive(true);
console.log(`TCP Client Connected ${TCPclient.localAddress}:${TCPclient.localPort}`);
var strData=JSON.stringify({"msg":"testRequest from Cortana"})
var is_buffer_null=TCPclient.write(strData);
if(is_buffer_null){
TCPclient.end();
}
TCPclient.on('data',(data)=>{
recvData+=data;
})
TCPclient.on('end',()=>{
console.log("Packet is received : "+recvData);
recvData='';
})
TCPclient.on('drain',()=>{
TCPclient.end();
})
TCPclient.on('error',(err)=>{
console.log(err);
})
TCPclient.on('close',(hardError)=>{
console.log("Client disconnected");
if(hardError){ console.log("TCP error"); }
})
})
TCPclient.js
var TCPcortana = net.connect({ port: 4040, host:'127.0.0.1',allowHalfOpen:true},()=>{
console.log(`server connected to ${TCPcortana.localAddress}:${TCPcortana.localPort} `);
});
TCPcortana.setKeepAlive(true);
TCPcortana.on('data',(data)=>{
recvData+=data;
})
TCPcortana.on('end',()=>{
console.log("Packet is received : "+recvData);
processReq(recvData);
recvData='';
})
TCPcortana.on('drain',()=>{
TCPcortana.end();
})
TCPcortana.on('error',(err)=>{
console.log(err);
setTimeout(()=>{
TCPcortana.connect({ port: 4040, host:'127.0.0.1',allowHalfOpen:true});
},10000)
})
TCPcortana.on('close',(hardError)=>{
console.log("connection disconnected");
if(hardError){ console.log("TCP error"); }
})
function processReq(data) {
console.log("Packet being processed");
var stringData=JSON.stringify(data);
var is_buffer_empty=TCPcortana.write(stringData);
if(is_buffer_empty){
TCPcortana.end();
}
}
the Tcp client send responses then the client connection close, i am expecting the client was not closed and keep alive the connection between and server and client... please help me...