To start a local server and handle HTTP requests to a specific URI in C++, you can use the Boost library's Asio module. Here is an example code that demonstrates this:
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
using namespace boost::asio;
class Server {
private:
io_service& io;
ip::tcp::acceptor acceptor;
public:
Server(io_service& io, int port)
: io(io), acceptor(io, ip::tcp::endpoint(ip::tcp::v4(), port))
{
startAccept();
}
void startAccept()
{
auto socket = std::make_shared<ip::tcp::socket>(io);
acceptor.async_accept(*socket, boost::bind(&Server::handleConnection, this, socket, boost::asio::placeholders::error));
}
void handleConnection(std::shared_ptr<ip::tcp::socket> socket, const boost::system::error_code& error)
{
if (!error)
{
boost::asio::streambuf request;
boost::asio::read_until(*socket, request, "\r\n\r\n");
std::string requestStr = boost::asio::buffer_cast<const char*>(request.data());
std::cout << "Received HTTP request: " << requestStr << std::endl;
std::string response = generateResponse(requestStr);
boost::asio::write(*socket, boost::asio::buffer(response));
}
startAccept();
}
std::string generateResponse(const std::string& request)
{
if (request.find("GET /uri HTTP/") != std::string::npos) {
return "HTTP/1.1 200 OK\r\n\r\nHello, World!";
}
return "HTTP/1.1 404 Not Found\r\n\r\n";
}
};
int main()
{
boost::asio::io_service io;
int port = 8080;
Server server(io, port);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
t.join();
return 0;
}
In the above code, we create a Server class that handles incoming connections. It uses the Boost library's io_service and ip::tcp to start the local server and accept incoming connections on the specified port.
The handleConnection function reads the incoming HTTP request and prints it to the console. It then generates a response based on the requested URI. In the example, if the request is for /uri, it responds with the message "Hello, World!" with a status code of 200 OK. Otherwise, it responds with a 404 Not Found status code.
The main function initializes the server and starts the Boost io_service to listen for incoming connections. A separate thread is created to handle the asynchronous operations.
To test the server, you can open a web browser and visit http://localhost:8080/uri. The browser should display the response message "Hello, World!".
Note: Make sure to link against the Boost library by adding -lboost_system to your compiler flags during the compilation process.