Skip to content

Network

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
find_package(Asio 1.21.0 QUIET)
if (NOT Asio_FOUND)
    FetchContent_Declare(asio GIT_REPOSITORY https://github.com/chriskohlhoff/asio.git GIT_TAG asio-1-21-0)
    FetchContent_GetProperties(asio)
    if (NOT asio_POPULATED)
        FetchContent_Populate(asio)
        add_library(asio INTERFACE)
        target_include_directories(asio INTERFACE ${asio_SOURCE_DIR}/asio/include)
        target_compile_definitions(asio INTERFACE ASIO_STANDALONE ASIO_NO_DEPRECATED)
        target_link_libraries(asio INTERFACE Threads::Threads)
    endif ()
endif()

1
2
add_executable(network network.cpp)
target_link_libraries(network asio)

1
2
3
4
5
// Object for network input and output
// - All networking programs at least one io_context
// - I/O execution context represents your program's link to the
//   operating system's I/O services
asio::io_context io_context;

1
2
3
4
// The acceptor listens for connections
// - Create the simplest server possible
asio::ip::tcp::endpoint ep(asio::ip::tcp::v4(), 8080);
asio::ip::tcp::acceptor acceptor(io_context, ep);

1
2
3
4
5
6
7
// For loop listening to connections from client
// - It will handle one connection at a time
// - See the async example for more than one connection at a time
while (true) {
    // Connection socket
    // - Represents the connection to the client
    asio::ip::tcp::socket socket(io_context);

1
2
3
4
// The acceptor listens for connections
// - Create the simplest server possible
asio::ip::tcp::endpoint ep(asio::ip::tcp::v4(), 8080);
asio::ip::tcp::acceptor acceptor(io_context, ep);

1
2
3
// - Transfer this information to the client with the socket
std::error_code error;
asio::write(socket, asio::buffer(message), error);

1
2
3
4
5
    if (error) {
        std::cout << "Error " << error.value() << ": "
                  << error.message() << std::endl;
    }
} // while (true)

Share Snippets