]> git.proxmox.com Git - ceph.git/blame - ceph/src/boost/libs/asio/example/cpp11/echo/blocking_tcp_echo_server.cpp
update sources to v12.2.3
[ceph.git] / ceph / src / boost / libs / asio / example / cpp11 / echo / blocking_tcp_echo_server.cpp
CommitLineData
7c673cae
FG
1//
2// blocking_tcp_echo_server.cpp
3// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4//
b32b8144 5// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
7c673cae
FG
6//
7// Distributed under the Boost Software License, Version 1.0. (See accompanying
8// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9//
10
11#include <cstdlib>
12#include <iostream>
13#include <thread>
14#include <utility>
15#include <boost/asio.hpp>
16
17using boost::asio::ip::tcp;
18
19const int max_length = 1024;
20
21void session(tcp::socket sock)
22{
23 try
24 {
25 for (;;)
26 {
27 char data[max_length];
28
29 boost::system::error_code error;
30 size_t length = sock.read_some(boost::asio::buffer(data), error);
31 if (error == boost::asio::error::eof)
32 break; // Connection closed cleanly by peer.
33 else if (error)
34 throw boost::system::system_error(error); // Some other error.
35
36 boost::asio::write(sock, boost::asio::buffer(data, length));
37 }
38 }
39 catch (std::exception& e)
40 {
41 std::cerr << "Exception in thread: " << e.what() << "\n";
42 }
43}
44
b32b8144 45void server(boost::asio::io_context& io_context, unsigned short port)
7c673cae 46{
b32b8144 47 tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port));
7c673cae
FG
48 for (;;)
49 {
b32b8144 50 std::thread(session, a.accept()).detach();
7c673cae
FG
51 }
52}
53
54int main(int argc, char* argv[])
55{
56 try
57 {
58 if (argc != 2)
59 {
60 std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
61 return 1;
62 }
63
b32b8144 64 boost::asio::io_context io_context;
7c673cae 65
b32b8144 66 server(io_context, std::atoi(argv[1]));
7c673cae
FG
67 }
68 catch (std::exception& e)
69 {
70 std::cerr << "Exception: " << e.what() << "\n";
71 }
72
73 return 0;
74}