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 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
using boost::asio::ip::tcp;
using namespace std;
static int id = 1;
const char message[] = "test write string...";
class echo_session
{
public:
echo_session(boost::asio::io_service& io_service)
: socket_(io_service)
{
id_ = id;
++id;
}
void start(const std::string& ip, const std::string& port)
{
tcp::resolver resolver(socket_.get_io_service());
tcp::resolver::query query(tcp::v4(), ip, port);
tcp::resolver::iterator iterator = resolver.resolve(query);
socket_.async_connect(*iterator, boost::bind(&echo_session::handle_connect, this, boost::asio::placeholders::error));
}
private:
void handle_connect(const boost::system::error_code& error)
{
if (!error)
{
//send
boost::asio::async_write(socket_,
boost::asio::buffer(message, sizeof(message)),
boost::bind(&echo_session::handle_write, this,
boost::asio::placeholders::error));
//ready to read
boost::asio::async_read(socket_, boost::asio::buffer(buf_, sizeof(buf_)),
boost::bind(&echo_session::handle_read, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
else
{
cout << "[CONNECT] " << error << endl;
delete this;
}
}
void handle_read(const boost::system::error_code& error, size_t bytes_transferred)
{
if (!error)
{
cout << id_ << ":receive:" << bytes_transferred << "," << buf_ << endl;
//cycle
handle_connect(error);
}
else
{
cout << "[READ] " << error << endl;
delete this;
}
}
void handle_write(const boost::system::error_code& error)
{
if (!error)
{
//do nothing
}
else
{
cout << "[WRITE] " << error << endl;
delete this;
}
}
int id_;
tcp::socket socket_;
char buf_[sizeof(message)];
};
int main(int argc, char* argv[])
{
const int session_num = 10000;
echo_session* sessions[session_num];
memset(sessions, 0, sizeof(sessions));
try
{
boost::asio::io_service io_service;
for (int i=0; i<session_num; ++i)
{
sessions[i] = new echo_session(io_service);
sessions[i]->start("127.0.0.1", "8008");
}
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "/n";
}
cout<<"stoppped"<<endl;
getchar();
return 0;
}
|