today i decided to make a basic web server that listens http requests with Boost.asio
Server.cpp Code:
#include <boost/asio.hpp>
#include <iostream>
using boost::asio::ip::tcp;
void session(tcp::socket socket) {
try {
for (;;) {
char data[1024];
boost::system::error_code error;
size_t length = socket.read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
boost::asio::write(socket, boost::asio::buffer(data, length));
}
} catch (std::exception& e) {
std::cerr << "Exception in thread: " << e.what() << "n";
}
}
void server(boost::asio::io_context& io_context, short port) {
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), port));
for (;;) {
tcp::socket socket(io_context);
acceptor.accept(socket);
std::thread(session, std::move(socket)).detach();
}
}
int main(int argc, char* argv[]) {
try {
if (argc != 2) {
std::cerr << "Usage: server <port>n";
return 1;
}
boost::asio::io_context io_context;
server(io_context, std::atoi(argv[1]));
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "n";
}
return 0;
}
CMakeLists.txt :
cmake_minimum_required(VERSION 3.10)
project(WebServer)
set(CMAKE_CXX_STANDARD 11)
find_package(Boost 1.70 REQUIRED COMPONENTS system)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(WebServer server.cpp)
target_link_libraries(WebServer ${Boost_LIBRARIES})
When I compiled the project I get the error :
CMake Error at CMakeLists.txt:7 (find_package):
By not providing "FindBoost.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a package configuration file provided by "Boost", but
CMake did not find one.
Could not find a package configuration file provided by "Boost" (requested
version 1.70) with any of the following names:
BoostConfig.cmake
boost-config.cmake
Add the installation prefix of "Boost" to CMAKE_PREFIX_PATH or set
"Boost_DIR" to a directory containing one of the above files. If "Boost"
provides a separate development package or SDK, be sure it has been
installed.
When i compiled and runned, servers crashes when some requestes come
Runtime Error :
Exception in thread: read_some: End of file
Exception in thread: Bad file descriptor
Exception in thread: Invalid argument
What i did:
- Installed Boost lib
- I runned Cmake building commands
- Tried to run the server
- I get error I tried other versions of Boost and Reconfigured the Cmake file but error continues
I think i have problem with boost or cmake