1 //
2 // stream_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 <array>
12 #include <cstdio>
13 #include <iostream>
14 #include <memory>
15 #include <boost/asio.hpp>
16
17 #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
18
19 using boost::asio::local::stream_protocol;
20
21 class session
22 : public std::enable_shared_from_this<session>
23 {
24 public:
session(stream_protocol::socket sock)25 session(stream_protocol::socket sock)
26 : socket_(std::move(sock))
27 {
28 }
29
start()30 void start()
31 {
32 do_read();
33 }
34
35 private:
do_read()36 void do_read()
37 {
38 auto self(shared_from_this());
39 socket_.async_read_some(boost::asio::buffer(data_),
40 [this, self](boost::system::error_code ec, std::size_t length)
41 {
42 if (!ec)
43 do_write(length);
44 });
45 }
46
do_write(std::size_t length)47 void do_write(std::size_t length)
48 {
49 auto self(shared_from_this());
50 boost::asio::async_write(socket_,
51 boost::asio::buffer(data_, length),
52 [this, self](boost::system::error_code ec, std::size_t /*length*/)
53 {
54 if (!ec)
55 do_read();
56 });
57 }
58
59 // The socket used to communicate with the client.
60 stream_protocol::socket socket_;
61
62 // Buffer used to store data received from the client.
63 std::array<char, 1024> data_;
64 };
65
66 class server
67 {
68 public:
server(boost::asio::io_context & io_context,const std::string & file)69 server(boost::asio::io_context& io_context, const std::string& file)
70 : acceptor_(io_context, stream_protocol::endpoint(file))
71 {
72 do_accept();
73 }
74
75 private:
do_accept()76 void do_accept()
77 {
78 acceptor_.async_accept(
79 [this](boost::system::error_code ec, stream_protocol::socket socket)
80 {
81 if (!ec)
82 {
83 std::make_shared<session>(std::move(socket))->start();
84 }
85
86 do_accept();
87 });
88 }
89
90 stream_protocol::acceptor acceptor_;
91 };
92
main(int argc,char * argv[])93 int main(int argc, char* argv[])
94 {
95 try
96 {
97 if (argc != 2)
98 {
99 std::cerr << "Usage: stream_server <file>\n";
100 std::cerr << "*** WARNING: existing file is removed ***\n";
101 return 1;
102 }
103
104 boost::asio::io_context io_context;
105
106 std::remove(argv[1]);
107 server s(io_context, argv[1]);
108
109 io_context.run();
110 }
111 catch (std::exception& e)
112 {
113 std::cerr << "Exception: " << e.what() << "\n";
114 }
115
116 return 0;
117 }
118
119 #else // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
120 # error Local sockets not available on this platform.
121 #endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
122