]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp03/echo/blocking_tcp_echo_server.cpp
add subtree-ish sources for 12.0.3
[ceph.git] / ceph / src / boost / libs / asio / example / cpp03 / 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 <boost/bind.hpp>
14 #include <boost/smart_ptr.hpp>
15 #include <boost/asio.hpp>
16 #include <boost/thread/thread.hpp>
17
18 using boost::asio::ip::tcp;
19
20 const int max_length = 1024;
21
22 typedef boost::shared_ptr<tcp::socket> socket_ptr;
23
24 void session(socket_ptr sock)
25 {
26 try
27 {
28 for (;;)
29 {
30 char data[max_length];
31
32 boost::system::error_code error;
33 size_t length = sock->read_some(boost::asio::buffer(data), error);
34 if (error == boost::asio::error::eof)
35 break; // Connection closed cleanly by peer.
36 else if (error)
37 throw boost::system::system_error(error); // Some other error.
38
39 boost::asio::write(*sock, boost::asio::buffer(data, length));
40 }
41 }
42 catch (std::exception& e)
43 {
44 std::cerr << "Exception in thread: " << e.what() << "\n";
45 }
46 }
47
48 void server(boost::asio::io_service& io_service, unsigned short port)
49 {
50 tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
51 for (;;)
52 {
53 socket_ptr sock(new tcp::socket(io_service));
54 a.accept(*sock);
55 boost::thread t(boost::bind(session, sock));
56 }
57 }
58
59 int main(int argc, char* argv[])
60 {
61 try
62 {
63 if (argc != 2)
64 {
65 std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
66 return 1;
67 }
68
69 boost::asio::io_service io_service;
70
71 using namespace std; // For atoi.
72 server(io_service, atoi(argv[1]));
73 }
74 catch (std::exception& e)
75 {
76 std::cerr << "Exception: " << e.what() << "\n";
77 }
78
79 return 0;
80 }