Click here to Skip to main content
15,441,629 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created the TCP socket server in node js. I want to send the received data packets to the webpage. My TCP server code is as follows

I want to read some data packets and display it on the webpage.
Data Packets example as follows:
$$1,,MH12JD1234,,863958045026874,,1.0.1,,PRTCL_1.0,,05032021,,114437,,18.465899,N,,73.782860,,E,,4624,,*


What I have tried:

// Node.js socket server script
const net = require('net');
var fs = require('fs');
// Create a server object
const server = net.createServer((socket) => {
    socket.on('data', (data) => {

        console.log('Data Received from : ' + socket.remoteAddress.toString() + ':' + socket.remotePort + ' Packet is: ' + data.toString());

        ExtractMessage(data);
        WriteDataToLog(data);
    });
    socket.write('SERVER: Hello! This is server speaking.<br>');
    //socket.end('SERVER: Closing connection now.<br>');

}).on('error', (err) => {
    console.error(err);
});
// Open server on port 9898
server.listen(9898, () => {
    console.log('opened server on', server.address().port);
});

server.addListener("connection", () => console.log("Connected."));

function ExtractMessage(data) {
    let datastr = data.toString();
    let arr = datastr.split(',,');
    console.log('Array Length: ', arr.length);
    //console.log('IMEI Number : ', arr[2]);


}

function WriteDataToLog(data) {
    fs.appendFile('Log.txt', '\n This is my message : ' + data.toString(), function(err) {
        if (err) throw err;

        console.log('Logged!');
    });
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900