我需要关心async_write呼叫套接字的生命周期吗?
Do I need to care about socket's lifetime in call to async_write?
我用这种方式调用asio::async_write:
namespace asio = boost::asio;
using asio::ip::tcp;
using std::string;
shared_pointer<tcp::socket> tcp_socket_pointer;
string message;
...
void send() {
asio::async_write(
*tcp_socket_pointer,
asio::buffer(message),
boost::bind(
&handle_send, // defined elsewhere
asio::placeholders::error,
asio::placeholders::bytes_transferred)
);
}
现在,在我的代码中,在对send
和handle_send
的调用之间,我传递的套接字可能会被破坏,因为tcp_socket_pointer
超出了它的作用域。
这合法吗?我的意思是,我需要确保引用的tcp::套接字在异步操作完成之前一直存在吗?我的直觉告诉我asio::async_write会立即进行系统调用,所以我不必担心,但我最好问:)。
如果它不能像我预期的那样工作,那么将tcp_socket_pointer
作为参数传递给handle_send
以确保它所指向的tcp::套接字不会过期是个好主意吗?
您可以使用它,但当tcp::socket
被销毁时,async_*
调用将被取消。
您可能希望将shared_ptr保留到套接字,并将其绑定到完成处理程序,以便它保留引用,这确实是您所描述的。
相关文章:
- 当套接字连接断开时检测C/C++Unix
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 如何在C/C++中用FD_set Unix设置套接字文件描述符
- 套接字读取后,我在缓冲区中看到意外输入
- 如何在CPP中创建应该在Windows和Linux上运行的套接字?
- 我可以与 python 服务器而不是 c++ 客户端建立 tcp/ip 套接字吗?
- 套接字连接"Operation not permitted"错误,甚至使用升压/平发器根.cpp
- WINAPI 注册应用程序重新启动时不清除打开的套接字
- (Winsock) UDP 接收工作正常,但同一套接字的发送失败
- MSG_WAITALL的套接字发送得到了 22 EINVAL
- C++套接字客户端到 Python 服务器未创建连接
- 在不知道套接字的情况下关闭网络连接
- C++套接字对不读/写父/子
- 非更新套接字消息
- SIGSEGV on Boost UDP 套接字关闭 - tcache_get at malloc.c.
- 将"uint8_t"(从套接字读取)隐式转换为"char"安全吗
- 当对套接字 send() 的同步调用由于连接另一端丢失而被阻止时,如何恢复?
- 当客户端在 write() 期间终止连接时,由对等套接字错误重置连接
- 我需要关心async_write呼叫套接字的生命周期吗?