如何使用 boost 冲洗插座
我正在实现一个使用 boost 向客户端发送 xml 的服务器。我面临的问题是缓冲区不会立即发送并累积到一个点然后发送整个内容。这会导致我的客户端出现问题,当它解析 xml 时,它可能有不完整的 xml 标签(不完整的消息)。 boost 有没有办法在需要发送消息时刷新套接字?下面是服务器的写入代码。
void
ClientConnection::handle_write(const boost::system::error_code& error)
{
if (!error)
{
m_push_message_queue.pop_front ();
if (!m_push_message_queue.empty () && !m_disconnected)
{
boost::asio::async_write(m_socket,
boost::asio::buffer(m_push_message_queue.front().data(),
m_push_message_queue.front().length()),
boost::bind(&ClientConnection::handle_write, this,
boost::asio::placeholders::error));
}
}
else
{
std::err << "Error writting out message...\n";
m_disconnected = true;
m_server->DisconnectedClient (this);
}
}
I am implementing a server that sends xml to clients using boost. The problem I am facing is that the buffer doesn't get sent immediately and accumulates to a point then sends the whole thing. This cause a problem on my client side, when it parses the xml, it may have incomplete xml tag (incomplete message). Is there a way in boost to flush out the socket whenever it needs to send out a message? Below is server's write code.
void
ClientConnection::handle_write(const boost::system::error_code& error)
{
if (!error)
{
m_push_message_queue.pop_front ();
if (!m_push_message_queue.empty () && !m_disconnected)
{
boost::asio::async_write(m_socket,
boost::asio::buffer(m_push_message_queue.front().data(),
m_push_message_queue.front().length()),
boost::bind(&ClientConnection::handle_write, this,
boost::asio::placeholders::error));
}
}
else
{
std::err << "Error writting out message...\n";
m_disconnected = true;
m_server->DisconnectedClient (this);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常,当使用 TCP 字节流创建应用程序时,发送方会发送固定长度的标头,以便接收方知道需要多少字节。然后接收器读取那么多字节并将生成的缓冲区解析为 XML 对象。
Typically when creating applications using TCP byte streams the sender sends a fixed length header so the receiver knows how many bytes to expect. Then the receiver reads that many bytes and parses the resulting buffer into an XML object.
我假设你正在使用 TCP 连接。 TCP 是流类型,因此您不能假设您的数据包将来自一个大数据包。您需要修复您的通信设计,首先发送大小长度(如 San Miller 答案),或者在发送所有 xml 数据后发送标志或分隔符。
I assume you are using TCP connection. TCP is stream type, so you can't assume your packet will come in one big packet. You need to fix your communication design, by sending size length first like San Miller answer, or sending flag or delimiter after all xml data has been sent.
假设您肯定要清除套接字上的一些数据,您可以执行以下操作:
其中
socket_
是一个成员变量。华泰
Assuming you are definitely going to have some data on the socket you want to clear, you could do something like this:
where
socket_
is a member variable.HTH