I’m new to Boost. I’m developing a little server. I have an issue when a client sends a message to my server. My server calls the function to read on the socket twice
this is the code in my client class
void ClientManager::ToRecv(void)
{
this->_socket.async_read_some(boost::asio::buffer(_buffer),
_strand.wrap(boost::bind(&ClientManager::HandleRead, this, boost::asio::placeholders::error))
);
}
void ClientManager::HandleRead(boost::system::error_code const & error)
{
_mutex.lock();
std::cout << boost::this_thread::get_id() << " client->HandleRead()" << std::endl;
for (unsigned int i = 0; i < _buffer.size(); ++i)
{
std::cout << _buffer[i]; // I display the message
}
std::cout << std::endl;
_mutex.unlock();
this->ToRecv();
}
When a client connects, I call the start function. This is what display in the console when I launch my server:
I create 3 threads.
Server Connect
[004FE200] Thread Start
[004FE238] Thread Start
[004FE7C8] Thread Start
and this is when i connect a putty client to my server
[004FE7C8] acceptor->NewClient()
[004FE7C8] client->Start()
and this is what my server displays when the client send “hello world”.
[004FE238] client->HandleRead()
hello world
[004FE7C8] client->HandleRead()
llo world
I don’t know what type _buffer is, but it should probably look like this, note
bytes_transferred.What’s with the mutex? Is that rly neccessary?
I would write it something like:
Now, what you will likely see (and have seen judging from your comments below) is the fact that
HandleRead()will be called multiple times with only parts of the message included. If you know the size of the message prior to calling thereadfunction, you can use the composed function async_read() instead. This is a free function in theboost::asionamespace.