How to communicate JSON data between C++ and Node.js ?


C++ is a powerful, high-performance language widely used for system-level programming and applications. At the same time, Node.js is an open-source, cross-platform JavaScript runtime environment commonly used for web applications.

By understanding the various methods for communicating JSON data between C++ and Node.js, developers can choose the best approach to their specific needs.

In this tutorial, we will explore the various ways to communicate JSON data between a C++ application and a Node.js server.

Three common approaches: using a RESTful API, using a message queue, and using a WebSocket

Users can follow the steps below to communicate JSON data between C++ and Node.js.

Using a RESTful API

Using a RESTful API involves the user creating a RESTful web service in Node.js that exposes a set of endpoints for C++ to interact with. The C++ application can then request HTTP to these endpoints to retrieve or update JSON data.

This approach is simple and easy to implement but can be less efficient than the other options.

Step 1 − First, users need to create a RESTful API in Node.js

Step 2 − Now, start making HTTP requests from C++. This can be done using a C++ library such as cURL. The user can create functions in the C++ application to handle requests.

Example – RESTful API

Here's an example of how the RESTful API approach can be implemented.

Create a RESTful API in Node.js -

const express = require('express');
const app = express();
const data = {"message": "hello world"};

app.get('/getData', (req, res) => {
   res.json(data);
});

app.post('/updateData', (req, res) => {
   data = req.body;
   res.json({ message: 'Data updated' });
});

app.listen(3000, () => {
   console.log('Server listening on port 3000');
});

Make HTTP requests from C++ −

#include <curl/curl.h>
#include <json/json.h>

Json::Value getData() {
   CURL *curl;
   CURLcode res;
   Json::Value jsonData;

   curl = curl_easy_init();
   if (curl) {
      curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:3000/getData");
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &parseJson);
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, &jsonData);
      res = curl_easy_perform(curl);
      curl_easy_cleanup(curl);
   }
   return jsonData;
}

void updateData(Json::Value jsonData) {
   CURL *curl;
   CURLcode res;
   struct curl_slist *headers = NULL;
   std::string jsonString = jsonData.toStyledString();

   headers = curl_slist_append(headers, "Content-Type: application/json");
   curl = curl_easy_init();
   if (curl) {
      curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:3000/updateData");
      curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonString.c_str());
      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
      res = curl_easy_perform(curl);
      curl_easy_cleanup(curl);
   }
}

Using the functions −

Json::Value jsonData = getData();
jsonData["newKey"] = "newValue";
updateData(jsonData);

Output

When users go in the ‘/getData’ route, they can see the below output printed in the console.

{"message":"hello world"}

Using a message queue

Using a message queue involves the user setting up a message queue service, such as RabbitMQ, to act as an intermediary between the C++ and Node.js applications. The C++ application can then send messages to the queue containing JSON data, which the Node.js application can consume.

This approach can provide a more efficient way to send data between the two applications, as it allows for asynchronous communication and can handle many messages.

Step 1 − The user needs to set up the message queue service and configure it to handle the communication between the two applications.

Step 2 − Now, the user can use a C++ library such as AMQP-CPP to send messages to the queue.

Step 3 − Next, the user can set up functionality to consume messages from the queue using a library such as ample.

Using a WebSocket

Using a WebSocket involves the user setting up a WebSocket server in Node.js and connecting to it from the C++ application. This allows for real-time, bidirectional communication between the two applications, with JSON data sent and received through the WebSocket connection.

This approach can be more efficient than the other options, as it allows for low-latency communication and eliminates the need for the C++ application to poll constantly for new data.

Step 1 − The user needs to set up a WebSocket server in Node.js and connect to it from the C++ application.

Step 2 − Once the WebSocket connection is established, the user can send and receive JSON data through the connection.

We learned several ways to communicate JSON data between C++ and Node.js, each with its advantages and disadvantages.

Users can choose the approach that best fits their needs, whether it be a simple RESTful API, a message queue for efficient communication, or a WebSocket for real-time bidirectional communication.

Updated on: 16-Feb-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements