Вот мой код асинхронного TCP-сервер'а, пишу его наподобие
кода-примера с сайта boost
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
using namespace boost::asio;
using namespace std;
class session
{
public:
session(io_service& service) : socket(service)
{
}
ip::tcp::socket& get_socket()
{
return socket;
}
void start()
{
socket.async_read_some(
boost::asio::buffer(buff, message_lenght),
boost::bind(
&session::read_handler,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
}
private:
ip::tcp::socket socket;
enum { message_lenght = 1024 };
char buff[message_lenght] = { };
void read_handler(
const boost::system::error_code& error,
std::size_t bytes_transferred
)
{
if (!error)
{
async_write(
socket,
boost::asio::buffer(buff, message_lenght),
boost::bind(
&session::write_handler,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
}
{
cout << "read error " << error.message() << endl;
delete this;
}
}
void write_handler(
const boost::system::error_code& error,
std::size_t bytes_transferred
)
{
if (!error)
{
socket.async_read_some(
boost::asio::buffer(buff, message_lenght),
boost::bind(
&session::read_handler,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
}
else
{
cout << "read error " << error.message() << endl;
delete this;
}
}
};
class server
{
public:
server(boost::asio::io_service& service, short port) : service_(),
acceptor(service, ip::tcp::endpoint(ip::tcp::v4(), port))
{
start_accept();
}
private:
short port;
io_service service_;
ip::tcp::acceptor acceptor;
void start_accept()
{
session* new_session = new session(service_);
acceptor.async_accept(
new_session->get_socket(),
boost::bind(
&server::handle_accept,
this,
new_session,
boost::asio::placeholders::error
)
);
}
void handle_accept(
session* new_session,
const boost::system::error_code& error
)
{
if (!error)
{
new_session->start();
}
else
{
cout << "accept error " << error.message() << endl;
delete new_session;
}
start_accept();
}
};
int main()
{
setlocale(LC_ALL, "Rus");
io_service service;
server* s = new server(service, 5000);
service.run();
}
Он принимает подключение, но не считывает сообщение от клиента.