c + +的boost ::支持ASIO :: async_write发送问题 [英] C++ boost::asio::async_write send problems

查看:369
本文介绍了c + +的boost ::支持ASIO :: async_write发送问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我称之为 async_write(),远程节点不接收数据,直到我称之为 async_write()再次。例如,我有3个数据包, A B C

When I call async_write(), the remote peer is not receiving data until I call async_write() again. For example, I have 3 packets, a, b, and c:

SendPacket(a); // the remote side receives nothing
SendPacket(b); // the remote side receives packet a
SendPacket(c); // the remote side receives packet b

这是我的code发送:

This is my code for sending:

void Session::SendPacket(packet p)
{
    dword len = p.Lenght(); 
    byte* buffer_send = new byte[len + 4]; //4 cause of the header

    memcpy(buffer_send + 4, p.GetRaw(), len); // copy everything to the buffer +4, 0-4 is header

    m_codec.EncodePacket(buffer_send, len);

    boost::asio::async_write(m_socket, boost::asio::buffer(buffer_send, len + 4),
                boost::bind(&Session::OnPacketSend, this, len + 4, boost::asio::placeholders::error,
                boost::asio::placeholders::bytes_transferred, buffer_send));

}

void Session::OnPacketSend(int len, const boost::system::error_code &e, size_t bytes_transferred, byte* buf)
{
    // this asynchronously fires when packet data is sent
    delete[] buf;
    if (e || bytes_transferred != len)
    {
        Stop();
        return;
    }
}

和我使用它是这样的:

packet pp;

pp.WriteWord(0);
pp.WriteDword(4);
pp.WriteWord(0);

SendPacket(pp);

此外,当命令sendpacket()接受按值而不是引用,发生崩溃。

Also, when SendPacket() accepts packet by value instead of reference, a crash occurs.

的Gr

推荐答案

当数据的少量正被写入到一个插座,如在原来的code(12字节〜),一个典型的观察的行为不被发送,直到随后的数据的数据被写入到插座因为 Nagle算法的。总之,许多系统将试图通过连接小出站消息到单个消息然后被发送到减轻的IP / TCP拥塞。要明确禁用在每个接口上此行为,设置的 的boost ::支持ASIO ::知识产权:: TCP :: no_delay 选项:

When small amounts of data are being written to a socket, such as in the original code (12 bytes~), one typically observes the behavior of data not being sent until subsequent data is written to the socket because of Nagle's algorithm. In short, many systems will attempt to mitigate IP/TCP congestion by concatenating small outbound messages into a single message that is then sent. To explicitly disable this behavior on a per-socket basis, set the boost::asio::ip::tcp::no_delay option:

boost::asio::ip::tcp::socket socket(io_service);
// ...
boost::asio::ip::tcp::no_delay option(true);
socket.set_option(option);

通过足够的带宽,禁用内格尔可能会导致更高的吞吐量。然而,它仍可能是值得研究的应用协议和逻辑得多,以确定何时或者什么数据可以被缓冲,并且当需要将其立即发送。

With sufficient bandwidth, disabling Nagle may result in higher throughput. Yet, it still may be worth examining the application protocol and logic much more to determine when or what data may be buffered, and when it needs to be immediately sent.

这篇关于c + +的boost ::支持ASIO :: async_write发送问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆