concept socket in category data

appears as: sockets, socket
Data Wrangling with JavaScript

This is an excerpt from Manning's book Data Wrangling with JavaScript.

The first problem we must solve is how to connect our sensor to our monitoring system. In the coming sections, we’ll cover two network-based mechanisms: HTTP POST and sockets. Both protocols build on the TCP network protocol and are directly supported by Node.js. Which protocol you choose depends on the frequency at which you expect data to be submitted.

Listing 12.2a Air pollution sensor that submits data to the server via a socket connection (listing-12.2/client/index.js)
// ... initial setup as per listing 12.1a ...

const serverHostName = "localhost";    #1  
const serverPortNo = 3030;    #1  

const client = new net.Socket();
client.connect(serverPortNo, serverHostName, () => {    #2  
    console.log("Connected to server!");
});

client.on("close", () => {    #3  
    console.log("Server closed the connection.");
});

importCsvFile(dataFilePath)    #4  
    .then(data => {
        let curIndex = 0;

 setInterval(() => {    #5  

                const outgoingData = Object.assign({}, data[curIndex]);
                curIndex += 1;

 const outgoingJsonData = JSON.stringify(outgoingData);    #6  

 client.write(outgoingJsonData);    #7  

            }, 1000);
    })
    .catch(err => {
        console.error("An error occurred.");
        console.error(err);
    });

#1   Sets up the server connection details
#2   Connects the socket to our Node.js server
#3   This callback is invoked when the server has closed the connection.
#4   Loads the example data from the CSV file
#5   Once per second, it sends a chunk of data to the server.
#6   Serializes outgoing data to JSON format
#7   Sends JSON data over the wire

In listing 12.2b, we have a new Node.js server that listens on a network port and accepts incoming socket connections. When our mock sensor (the client) connects, we set a handler for the socket’s data event. This is how we intercept incoming data; we’re also starting to see that event-based architecture that I mentioned earlier. In this example, as before, we print the data to the console to check that it has come through correctly.