]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | // |
2 | // blocking_tcp_echo_server.cpp | |
3 | // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
4 | // | |
1e59de90 | 5 | // Copyright (c) 2003-2022 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> | |
f67539c2 | 13 | #include <boost/bind/bind.hpp> |
7c673cae FG |
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 | ||
b32b8144 | 48 | void server(boost::asio::io_context& io_context, unsigned short port) |
7c673cae | 49 | { |
b32b8144 | 50 | tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port)); |
7c673cae FG |
51 | for (;;) |
52 | { | |
b32b8144 | 53 | socket_ptr sock(new tcp::socket(io_context)); |
7c673cae FG |
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 | ||
b32b8144 | 69 | boost::asio::io_context io_context; |
7c673cae FG |
70 | |
71 | using namespace std; // For atoi. | |
b32b8144 | 72 | server(io_context, atoi(argv[1])); |
7c673cae FG |
73 | } |
74 | catch (std::exception& e) | |
75 | { | |
76 | std::cerr << "Exception: " << e.what() << "\n"; | |
77 | } | |
78 | ||
79 | return 0; | |
80 | } |