]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp03/echo/blocking_tcp_echo_server.cpp
2 // blocking_tcp_echo_server.cpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
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)
13 #include <boost/bind/bind.hpp>
14 #include <boost/smart_ptr.hpp>
15 #include <boost/asio.hpp>
16 #include <boost/thread/thread.hpp>
18 using boost::asio::ip::tcp
;
20 const int max_length
= 1024;
22 typedef boost::shared_ptr
<tcp::socket
> socket_ptr
;
24 void session(socket_ptr sock
)
30 char data
[max_length
];
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.
37 throw boost::system::system_error(error
); // Some other error.
39 boost::asio::write(*sock
, boost::asio::buffer(data
, length
));
42 catch (std::exception
& e
)
44 std::cerr
<< "Exception in thread: " << e
.what() << "\n";
48 void server(boost::asio::io_context
& io_context
, unsigned short port
)
50 tcp::acceptor
a(io_context
, tcp::endpoint(tcp::v4(), port
));
53 socket_ptr
sock(new tcp::socket(io_context
));
55 boost::thread
t(boost::bind(session
, sock
));
59 int main(int argc
, char* argv
[])
65 std::cerr
<< "Usage: blocking_tcp_echo_server <port>\n";
69 boost::asio::io_context io_context
;
71 using namespace std
; // For atoi.
72 server(io_context
, atoi(argv
[1]));
74 catch (std::exception
& e
)
76 std::cerr
<< "Exception: " << e
.what() << "\n";