我有一个客户端应用程序通过 tcp 发送数据。在某些时候,对 send() 的调用在未发送所有可用字节的情况下返回,而对 send 的下一次调用将关闭应用程序而不会出现任何类型的错误。
调用 send() 的循环如下所示:
// m_buf is an std::vector of size 65536
auto total_bytes = fill_buffer(m_buf.data(),m_buf.size());
while(total_bytes > 0){
// m_socket is a straightforward wrapper around a socket descriptor that
// throws if a call to send() returns an error.
auto total_bytes_sent = m_socket.send(m_buf.data(),total_bytes);
auto remaining_bytes = total_bytes - total_bytes_sent;
while(remaining_bytes > 0){
total_bytes_sent += m_socket.send(m_buf.data()+total_bytes_sent,remaining_bytes);
remaining_bytes = total_bytes - total_bytes_sent;
}
total_bytes = fill_buffer(m_buf.data(),m_buf.size());
}
我还得到了一些调试打印:
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 65536
send: remaining_bytes 0
send: total_bytes 65536
send: total_bytes_sent 8127
send: remaining_bytes 57409
[computer@localhost test]$
最后,调用了 send() 来发送 remaining_bytes,但调用永远不会返回(也没有捕获到异常)并且应用程序关闭。
最佳答案
一种可能是您从 send() 收到错误返回,但您没有检查 -1。这可能会使 total_bytes_sent 成为负数,这会使您的第二次发送进入无效内存。
关于c++ - 调用 send() 无错误地关闭应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55162779/