]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp11/echo/blocking_tcp_echo_server.cpp
add subtree-ish sources for 12.0.3
[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-2016 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_service& io_service, unsigned short port)
46 {
47 tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
48 for (;;)
49 {
50 tcp::socket sock(io_service);
51 a.accept(sock);
52 std::thread(session, std::move(sock)).detach();
53 }
54 }
55
56 int main(int argc, char* argv[])
57 {
58 try
59 {
60 if (argc != 2)
61 {
62 std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
63 return 1;
64 }
65
66 boost::asio::io_service io_service;
67
68 server(io_service, std::atoi(argv[1]));
69 }
70 catch (std::exception& e)
71 {
72 std::cerr << "Exception: " << e.what() << "\n";
73 }
74
75 return 0;
76 }