gpt4 book ai didi

c++ - 套接字超时 : select vs setsockopt

转载 作者:行者123 更新时间:2023-12-04 13:27:01 28 4
gpt4 key购买 nike

我正在使用超时在套接字上发送和接收数据。我发现可以通过将套接字设置为非阻塞模式并使用 select 来实现超时。或使用 setsockoptSO_SNDTIMEO/SO_RCVTIMEO选项。
这两种方法之间有什么区别,对于 ,是否有任何理由更喜欢一种实现而不是另一种实现? Linux (Redhat) 和 视窗 ?

最佳答案

What are the differences between these two methods and is there any reason to prefer one implementation over the other both for Linux (Redhat) and Windows?


对于 Linux,差异似乎相当小:

Specify the receiving or sending timeouts until reporting an error. The argument is a struct timeval. If an input or output function blocks for this period of time, and data has been sent or received, the return value of that function will be the amount of data transferred; if no data has been transferred and the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK, or EINPROGRESS (for connect(2)) just as if the socket was specified to be nonblocking. If the timeout is set to zero (the default) then the operation will never timeout. Timeouts only have effect for system calls that perform socket I/O (e.g., read(2), recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for select(2), poll(2), epoll_wait(2), and so on.


Source
但是,您没有方便的属性来同时多路复用多个连接,例如, select .
对于 Windows,差异更为严重:

The timeout, in milliseconds, for blocking send calls. The default forthis option is zero, which indicates that a send operation will nottime out. If a blocking send call times out, the connection is in anindeterminate state and should be closed. If the socket is createdusing the WSASocket function, then the dwFlags parameter must have theWSA_FLAG_OVERLAPPED attribute set for the timeout to functionproperly. Otherwise the timeout never takes effect.


Source
因此,超时后,套接字将无法使用(这可能不是您想要的行为)。
仅因为此行为在两个 Berkely 套接字实现之间不同,我不建议使用 setsockopt(SO_SNDTIMEO/SO_RCVTIMEO)但是使用为此而创建的设施,例如 select ,或者更好的是像 boost::asio 这样合适的网络套接字库。

关于c++ - 套接字超时 : select vs setsockopt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67882330/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com