1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <vector>
#include "connection.hpp" // Must come before boost/serialization headers.
#include <boost/serialization/vector.hpp>
#include "stock.hpp"
/// Downloads stock quote information from a server.
class client
{
private:
boost::asio::ip::udp::socket sock;
/// The data received from the server.
std::vector<stock> stocks_;
boost::asio::ip::udp::resolver resolver;
boost::asio::ip::udp::resolver::query query;
boost::asio::ip::udp::resolver::iterator it;
char data[1024];
public:
/// Constructor starts the asynchronous connect operation.
client(boost::asio::io_service& io_s,
const std::string host, const std::string& port)
: sock(io_s, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 0)),
resolver(io_s),
query(boost::asio::ip::udp::v4(), host.c_str(), port.c_str())
{
std::cout<<"Starting.\n";
it = resolver.resolve(query);
sock.send_to(boost::asio::buffer("0",1),*it);
boost::asio::ip::udp::endpoint sender_endpoint;
/// Holds the outbound data.
std::string outbound_data_;
/// Holds the inbound data.
std::vector<char> inbound_data_;
size_t length = sock.receive_from(boost::asio::buffer(data, 1024), sender_endpoint);
std::string archive_data(&data[0], length);
std::istringstream archive_stream(archive_data);
boost::archive::text_iarchive archive(archive_stream);
archive >> stocks_;
std::cout<<"Data in raw: \n";
std::cout.write(data,length);
for (std::size_t i = 0; i < stocks_.size(); ++i)
{
std::cout << "Stock number " << i << "\n";
std::cout << " code: " << stocks_[i].code << "\n";
std::cout << " name: " << stocks_[i].name << "\n";
std::cout << " open_price: " << stocks_[i].open_price << "\n";
std::cout << " high_price: " << stocks_[i].high_price << "\n";
std::cout << " low_price: " << stocks_[i].low_price << "\n";
std::cout << " last_price: " << stocks_[i].last_price << "\n";
std::cout << " buy_price: " << stocks_[i].buy_price << "\n";
std::cout << " buy_quantity: " << stocks_[i].buy_quantity << "\n";
std::cout << " sell_price: " << stocks_[i].sell_price << "\n";
std::cout << " sell_quantity: " << stocks_[i].sell_quantity << "\n";
}
std::cout<<"Done.\n";
}
};
int main(int argc, char* argv[])
{
try
{
// Check command line arguments.
if (argc != 3)
{
std::cerr << "Usage: client <host> <port>" << std::endl;
return 1;
}
boost::asio::io_service io_service;
client client(io_service, argv[1], argv[2]);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
| |