Boost.Asio:从SSL-Socket读取输入会导致不完整的数据 [英] Boost.Asio: Reading input from SSL-Socket results in incomplete data
问题描述
我有一个名为 NIUserSession
的类,它处理与客户端的SSL加密连接。这是它,虽然我删除了与我的问题不相关的一切:
I have a class called NIUserSession
which handles a SSL-encrypted connection with a client. This is it, although I removed everything which is not relevant for my question:
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssl_socket;
class NIUserSession
{
public:
/*....*/
void readUntil(std::string until);
/*....*/
private:
/*....*/
void readHandler(const boost::system::error_code& error, std::size_t bytes_transferred);
ssl_socket socket_;
boost::asio::streambuf readBuffer;
/*....*/
};
void NIUserSession::readUntil(std::string until)
{
boost::asio::async_read_until(this->socket_, this->readBuffer, until, boost::bind(&NIUserSession::readHandler,
this,
boost::asio::placeholders::error(),
boost::asio::placeholders::bytes_transferred()));
}
void NIUserSession::readHandler(const boost::system::error_code &error, std::size_t bytes_transferred)
{
if(!error)
{
std::cout << "Bytes transfered: " << bytes_transferred << std::endl;
this->readBuffer.commit(bytes_transferred);
std::istream istrm(&this->readBuffer);
std::string message;
istrm >> message;
std::cout << "Message: " << message << std::endl;
} else {
// ...
}
}
现在客户端连接,ssl握手等,然后从 NIUserSession
内执行此行:
Now a client connects, ssl handshake, etc., and then this line is executed from within NIUserSession
:
this-> readUntil(< EOF>);
等待客户端发送消息并以< EOF>
结束。
The server should now wait until the client sends a message and ends it with <EOF>
.
从我的客户端应用程序,我发送以下(JSON)数据:
From my client application, I send the following (JSON) data:
服务器输出:
Bytes transfered: 169
Message: {
可以看到,169个字节被传输, strong> 1 字符出现在输出中。我想我做错了与 boost :: asio :: streambuf
(我从来没有使用它之前)。
As you can see, 169 bytes are transfered but only 1 character appears in the output. I think I am doing something wrong with the boost::asio::streambuf
(I never used it before).
推荐答案
此行:
istrm >> message;
从流中读取由空格分隔的字符串。第一个{是由空格分隔的字符串。您只需要继续阅读 istrm
。
reads a string delimited by whitespace from the stream. That first "{" is a string delimited by whitespace. You just need to keep reading from istrm
.
而不是使用 operator>
,您可以使用 boost :: asio :: buffers_begin()
获取一个随机访问迭代器,然后使用两个迭代器。这看起来像这样(未测试):
Instead of using operator>>
, you can copy the indicated number of bytes to a string by using boost::asio::buffers_begin()
to get a random access iterator, and then constructing the string with two iterators. That would look something like this (untested):
const auto bufferIterator = boost::asio::buffers_begin(this->readBuffer.data());
const std::string message(bufferIterator, bufferIterator + bytes_transferred);
this->readBuffer.consume(bytes_transferred);
这篇关于Boost.Asio:从SSL-Socket读取输入会导致不完整的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!