5 // Copyright (c) 2003-2014 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)
11 #include <boost/asio.hpp>
12 #include <boost/bind.hpp>
13 #include <boost/lexical_cast.hpp>
16 #include "connection.hpp" // Must come before boost/serialization headers.
17 #include <boost/serialization/vector.hpp>
20 namespace s11n_example {
22 /// Serves stock quote information to any client that connects to it.
26 /// Constructor opens the acceptor and starts waiting for the first incoming
28 server(boost::asio::io_service& io_service, unsigned short port)
29 : acceptor_(io_service,
30 boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
32 // Create the data to be sent to each client.
35 s.name = "A Big Company";
41 s.buy_quantity = 1000;
43 s.sell_quantity = 2000;
46 s.name = "Developer Entertainment Firm";
52 s.buy_quantity = 34000;
54 s.sell_quantity = 45000;
57 // Start an accept operation for a new connection.
58 connection_ptr new_conn(new connection(acceptor_.get_io_service()));
59 acceptor_.async_accept(new_conn->socket(),
60 boost::bind(&server::handle_accept, this,
61 boost::asio::placeholders::error, new_conn));
64 /// Handle completion of a accept operation.
65 void handle_accept(const boost::system::error_code& e, connection_ptr conn)
69 // Successfully accepted a new connection. Send the list of stocks to the
70 // client. The connection::async_write() function will automatically
71 // serialize the data structure for us.
72 conn->async_write(stocks_,
73 boost::bind(&server::handle_write, this,
74 boost::asio::placeholders::error, conn));
77 // Start an accept operation for a new connection.
78 connection_ptr new_conn(new connection(acceptor_.get_io_service()));
79 acceptor_.async_accept(new_conn->socket(),
80 boost::bind(&server::handle_accept, this,
81 boost::asio::placeholders::error, new_conn));
84 /// Handle completion of a write operation.
85 void handle_write(const boost::system::error_code& e, connection_ptr conn)
87 // Nothing to do. The socket will be closed automatically when the last
88 // reference to the connection object goes away.
92 /// The acceptor object used to accept incoming socket connections.
93 boost::asio::ip::tcp::acceptor acceptor_;
95 /// The data to be sent to each client.
96 std::vector<stock> stocks_;
99 } // namespace s11n_example
101 int main(int argc, char* argv[])
105 // Check command line arguments.
108 std::cerr << "Usage: server <port>" << std::endl;
111 unsigned short port = boost::lexical_cast<unsigned short>(argv[1]);
113 boost::asio::io_service io_service;
114 s11n_example::server server(io_service, port);
117 catch (std::exception& e)
119 std::cerr << e.what() << std::endl;