Boost async_read_some usage
When async_read_some reads the data, it will directly call back the set function, regardless of whether the data has been read or not. So here it is.
You will encounter a very thorny problem, how to make sure that the data has been read? A common way is to add after the data
Flag bits, such as adding / r/n/r/n as a Terminator, and then stop reading
The basic principle of async_read_some is to add an asynchronous task to the queue of IOCP. When there is nothing to do, CSession::ContinueRead
Should not be called
Class CSession: public boost::enable_shared_from_this
{
Public:
CSession (boost::asio::io_service & io_service): m_socket (io_service)
{
Memset (m_szRecvBuffer, 0x00, 1024)
M_bStartRecv = false
}
Void Start ()
{
Static boost::asio::ip::tcp::no_delay option (true)
M_socket.set_option (option)
Boost::function0 f = boost::bind (& CSession::StartThread, this)
Boost::thread thrd (f)
}
/ *
The root cause of starting the thread function is that you need to push the message to the client and wait for the message to be received in the process.
, /
Void StartThread ()
{
While (true)
{
/ *
The main purpose of using the m_bStartRecv flag bit is to avoid setting callbacks many times, and there is no need to set callbacks when receiving them.
, /
If (! m_bStartRecv)
{
M_bStartRecv = true
M_socket.async_read_some (boost::asio::buffer (m_szRecvBuffer))
Boost::bind (& CSession::ContinueRead, shared_from_this ())
Boost::asio::placeholders::error
Boost::asio::placeholders::bytes_transferred))
}
Char szAlarm [32] = "alarm"
Boost::system::error_code ec
M_socket.send (boost::asio::buffer (szAlarm), 0, ec)
Boost::this_thread::sleep_for (boost::chrono::milliseconds (3000))
If (ec) break
}
}
Private:
/ *
In the current receive callback function, we also continue to set the callback function m_socket.async_read_some to avoid reading only part of the packet
Here, m_szRecvBuffer will always act as a buffer for reception, and the previously received data is also in it, and the rest of the data will be populated to the
After m_szRecvBuffer, the bytes_transferred parameter represents the data currently received
, /
Void ContinueRead (const boost::system::error_code & error, std::size_t bytes_transferred)
{
If (error) return
M_strMatch = m_strMatch + m_szRecvBuffer
Int index = m_strMatch.find ("\ r\ n\ r\ n", 0)
If (- 1! = index)
{
Int ret = m_socket.send (boost::asio::buffer (m_szRecvBuffer))
Std::cout