Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ rest sdk http_listener as a network server

How to configure http_listener to listen on my ip address so other computers on the network can send requests to the server ?

http_listener listener(L"http://localhsot:9000"); // not working
http_listener listener(L"http://0.0.0.0:9000"); // run time error
http_listener listener(L"http://*:9000");       // run time error

I want to use c++ rest sdk as a server on my local network .

like image 376
amin Avatar asked Mar 22 '23 04:03

amin


2 Answers

The reason why http_listener listener(L"http://localhsot:9000");

isn't working is because "localhost" is spelled wrong.

Once you correct the misspelling, you should be able to point your web browser to http://localhost:9000 and you'll receive the request. Test it with a print function.

As mentioned, don't forget to set up the support for the request.

Listener.support(methods::GET, std::bind(&HandleGet, this, std::placeholders::_1));

and the HandleGet function (if GET request)

HandleGet(http_request request)
{
   std::wcout << L"Received GET request" << std::endl;
}

So after this has been setup, point your web browser to the address, and you should see the output.

Also, you can wrap the ServerInit.open().wait() (starts the listening) in a try/catch to see why it's not working.

like image 63
granteous Avatar answered Mar 23 '23 20:03

granteous


Being the author, I can highly recommend Restbed. It is an open-source project written in C++11 with the goal of reaching HTTP(s) 1.0-2.0 compliance.

#include <memory>
#include <cstdlib>
#include <restbed>

using namespace std;
using namespace restbed;

void get_method_handler( const shared_ptr< Session >& session )
{
    const auto request = session->get_request( );

    size_t content_length = 0;
    request->get_header( "Content-Length", content_length );

    session->fetch( content_length, [ ]( const shared_ptr< Session >& session,
                                         const Bytes& body )
    {
        fprintf( stdout, "%.*s\n", ( int ) body.size( ), body.data( ) );

        session->close( OK, "Hello, World!", { { "Content-Length", "13" } } );
    } );
}

int main( const int, const char** )
{
    auto resource = make_shared< Resource >( );
    resource->set_path( "/resource" );
    resource->set_method_handler( "GET", get_method_handler );

    auto settings = make_shared< Settings >( );
    settings->set_port( 1984 );
    settings->set_default_header( "Connection", "close" );

    Service service;
    service.publish( resource );
    service.start( settings );

    return EXIT_SUCCESS;
}

See here for more examples.

like image 23
Ben Crowhurst Avatar answered Mar 23 '23 18:03

Ben Crowhurst