我需要实现以下行为:服务器启动时,应使用广播检查现有服务器。然后它等待答案。

但是,如何设置等待超时时间?

int optval = 1;
char buff[BUFF_SIZE];
SOCKADDR_IN addr;
int length = sizeof(addr);

if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&optval, sizeof(optval)) == SOCKET_ERROR) throw(errors::SETSOCKOPT);

addr->sin_family = AF_INET;
addr->sin_port = htons(this->serverPort);
addr->sin_addr.s_addr = INADDR_ANY;
sendto(s, this->serverName.c_str(), this->serverName.length() + 1, NULL, (SOCKADDR*)&addr, sizeof(addr));

memset(&addr, NULL, sizeof(addr));

recvfrom(s, buff, BUFF_SIZE, NULL, (SOCKADDR*)&addr, &length);

最佳答案

setsockopt()SO_RCVTIMEO设置读取超时,并处理EAGAIN/EWOULDBLOCK如果触发超时则发生。

关于c++ - C++ recvfrom超时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39840877/

10-13 06:28