]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp11/echo/blocking_tcp_echo_server.cpp
update source to Ceph Pacific 16.2.2
[ceph.git] / ceph / src / boost / libs / asio / example / cpp11 / echo / blocking_tcp_echo_server.cpp
1 //
2 // blocking_tcp_echo_server.cpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
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
17 using boost::asio::ip::tcp;
18
19 const int max_length = 1024;
20
21 void 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
45 void server(boost::asio::io_context& io_context, unsigned short port)
46 {
47 tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port));
48 for (;;)
49 {
50 std::thread(session, a.accept()).detach();
51 }
52 }
53
54 int 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
64 boost::asio::io_context io_context;
65
66 server(io_context, std::atoi(argv[1]));
67 }
68 catch (std::exception& e)
69 {
70 std::cerr << "Exception: " << e.what() << "\n";
71 }
72
73 return 0;
74 }