这次做的这个项目就遇到一些问题
想要达到的效果是每次先读取100字节的内容,之后根据这里面的数据长度的提示去找到接下来需要继续读出来的数据长度是多少,但是还是遇到了一些问题没有解决。所以又回头去看了一下API到底都是怎么回事。
首先我之前使用的是ip::tcp::socket::async_read_some()
basic_stream_socket::async_read_some
This function is used to asynchronously read data from the stream socket. The function call always returns immediately.
这个函数是用来异步读取来自一个流套接字的数据的函数,并且这个函数调用之后通常会迅速的返回。其实对于异步函数来说,基本上调用了之后都会立即返回,然后读取到数据之后才会调用回调函数进行判断。
函数原型
template< typename MutableBufferSequence, typename ReadHandler> DEDUCED
async_read_some( const MutableBufferSequence & buffers, ReadHandler && handler);
handler
The handler to be called when the read operation completes. Copies will be made of the handler as required. The function signature of the handler must be:
void handler(
const boost::system::error_code& error, // Result of operation.
std::size_t bytes_transferred // Number of bytes read.
);
Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_context::post()
.
无论异步操作是否立即完成,都不会从此函数内调用处理程序。处理程序的调用将以与使用boost::asio::io_context::post()相同的方式执行。
重点提示
The read operation may not read all of the requested number of bytes. Consider using the async_read
function if you need to ensure that the requested amount of data is read before the asynchronous operation completes.
async_read_some可能无法读取所有请求的字节数。如果需要确保在异步操作完成之前读取请求的数据量,请考虑使用async_read
函数。
我之前使用的就是这个函数,也就是说这个函数不会严格按照data的规定字节数去读取,毕竟只是read_some而已......又不是read_all
template<
typename AsyncReadStream,
typename MutableBufferSequence,
typename ReadHandler>
DEDUCED async_read(
AsyncReadStream & s,
const MutableBufferSequence & buffers,
ReadHandler && handler,
typename enable_if< is_mutable_buffer_sequence< MutableBufferSequence >::value >::type * = 0);
Start an asynchronous operation to read a certain amount of data from a stream.
开始一个异步的读取操作来从字节流里面读取一定数量的数据
This function is used to asynchronously read a certain number of bytes of data from a stream. The function call always returns immediately. The asynchronous operation will continue until one of the following conditions is true:
- The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
- An error occurred.
也就是说如果读取到的数据已经满了,bytes transferred 和buffer size一样大的时候就会发生继续触发异步函数的情况
所以也就有下面的警告
This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. The program must ensure that the stream performs no other read operations (such as async_read, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.
意思就是这个函数表面上你调用了一次但是其实它是一堆函数的组合,只要满足以上的要求就会接着触发异步操作,所以不能在async_read调用的时候再去调用什么read函数之类的。
但是其实不接着往下读取的话它也不会自己去调用,所以我想这个是在说多线程的时候调用不安全?略有疑问