Is there any known way to send strings or data from a html page to a c++ application?

I am new to this area and just wanted to know if this sort of thing is possible. I can’t seem to find much only about it. The only thing I could think of was a javascript backend that communicates to a C++ application.

I looked at Qwidget toolkits for C++, yet I could not find any example of this online.

Ultimately I’m trying to take a html page (served using node.JS) and to have a button, that when clicked, sends a string of data to a c++ application.

I’m not sure how I’d implement POST or GET requests into this and if using a javascript backend is the way to go.

If anyone has come across this sort of method before, and could point me in the right direction, or even to a useful resource or example I’d really appreciate it.

Answer

You can use cpprest. Just create http server on localhost and send POST, GET or OPTIONS requests. It will take up less than one percent of the CPU.

Example:

httpserver.h

#ifndef HTTPSERVER_H
#define HTTPSERVER_H

#include <cpprest/producerconsumerstream.h>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <iphlpapi.h>
#include <Assert.h>
#include <iostream>
#include <iomanip>
#include <sstream>

#pragma comment(lib, "iphlpapi.lib")

using namespace std;
using namespace web;
using namespace http;
using namespace utility;
using namespace concurrency;
using namespace http::experimental::listener;

class HttpServer : public http_listener
{

public:
    HttpServer();
    ~HttpServer();

    //http request
private:
    void HandleGet(http_request request);
    void HandlePost(http_request request);
    void HandleOptions(http_request request);

    json::value ProcessRequest(json::value task);

private:
    //user info
    wstring data;
};


#endif

httpserver.cpp

#include "HttpServer.h"

HttpServer::HttpServer()
    : http_listener(L"http://localhost:9999"s)
{
    data= L"";

    //setting up the server
    this->support(methods::GET, bind(&HttpServer::HandleGet, this, placeholders::_1));
    this->support(methods::POST, bind(&HttpServer::HandlePost, this, placeholders::_1));
    this->support(methods::OPTIONS, bind(&HttpServer::HandleOptions, this, placeholders::_1));

}

HttpServer::~HttpServer()
{this->close();}

void HttpServer::HandleGet(http_request request)
{
    json::value jsonResponse(L"Get response from C++");
    http_response response(status_codes::OK);
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.set_body(jsonResponse);
    request.reply(response);
}

void HttpServer::HandlePost(http_request request)
{
    json::value jsonResponse;
    request.extract_json().then([&jsonResponse, this, &request](pplx::task<json::value> task)
    {
        jsonResponse = this->ProcessRequest(task.get());
    }).wait();

    //write status into http response
    http_response response(status_codes::OK);

    //if you need to add CORS into headers
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.set_body(jsonResponse);
    request.reply(response);
}

void HttpServer::HandleOptions(http_request request)
{
    http_response response(status_codes::OK);
    response.headers().add(U("Allow"), U("GET, POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.headers().add(U("Access-Control-Allow-Methods"), U("GET, POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
    request.reply(response);

    return;
}

json::value HttpServer::ProcessRequest(json::value task)
{
        for (auto iterator = task.as_object().cbegin(); iterator != task.as_object().cend(); ++iterator)
        {
            const wstring& key = iterator->first;
            const json::value& value = iterator->second;

            if (key == L"data")
            {
                data = value.as_string();
                continue;
            }

            //if you need to send response
            response[L"response"] = json::value::boolean(true);
        }

    return response;
}

main.cpp

int main(int argc, char* argv[])
{
    ::ShowWindow(::GetConsoleWindow(), SW_HIDE);

    unique_ptr<HttpServer> webServer = make_unique<HttpServer>();
    //listen 9999 port
    webServer->open().wait();

    while(true)
        this_thread::sleep_for(chrono::seconds(1));  //Simulate some work by sleeping

    return 0;
}

On the client side:

function requestREST(request/*json data*/,onSuccess/*callback with json response*/) {    
    $.ajax({     
        type: "POST",
        url: "...",
        data: JSON.stringify(request),
        dataType: 'json',
        crossDomain: true,
        contentType: "application/json",
        success: function (response) {
            onSuccess(response);
        },
        timeout:3000,
        statusCode: {
            400: function (response) {
                alert('Not working!');
            },
            0: function (response) {
                alert('Not working!');
            }              
        }
    });