我想问一下,如何让套接字客户端反复等待服务器。例如,如果套接字服务器没有运行,那么客户端在connect()期间等待大约1-3秒,然后抛出错误10038(WSAENOTSOCK)。如果服务器准备好了,那么它连接。
我希望客户端在服务器不可达时等待。是否有任何标志?我尝试将connect()放入while()循环,但没有用。
下面是重要的fromcode
#define SOCKET_DEFAULT_PROTOCOL SOCK_STREAM
typedef struct dev_socket {
std::string ip = "";
std::thread openner;
unsigned short port = 0;
SOCKET num = 0, external_num = 0;
}dev_socket;
int openClientSocket(dev_socket &io, std::string server_ipv4, unsigned short port) {
char *server_name = (server_ipv4.empty() ? localhost_addr : const_cast<char*>(server_ipv4.c_str()));
int retval, socket_type = SOCKET_DEFAULT_PROTOCOL;
struct sockaddr_in server;
struct hostent *hp;
#if defined(_WIN32)
int fromlen;
#else
socklen_t fromlen;
#endif
#if defined(_WIN32)
WSADATA wsaData;
if ((retval = WSAStartup(MAKEWORD(2, 0), &wsaData)) != 0) {
cout << "ERROR! Client: WSAStartup() failed (socket number " + std::to_string(io.num) +
") with error " + std::to_string(retval) + ".\n";
WSACleanup();
return 1;
}
#endif
// Attempt to detect if we should call gethostbyname() or gethostbyaddr()
hp = gethostbyname(server_name);
if (hp == NULL) {
cout << "ERROR! Client: Cannot resolve address \"" + (std::string)(server_name) + "\": Error.\n";
cleenup();
return 1;
}
//Creating SOCKET
// Copy the resolved information into the sockaddr_in structure
memset(&server, 0, sizeof(server));
memcpy(&(server.sin_addr), hp->h_addr, hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = htons(port);
io.num = socket(AF_INET, socket_type, 0); /* Open a socket */
if (io.num < 0) {
cout << "ERROR! Client: Error Opening socket number " + std::to_string(io.num) + ". " + getSocketErrorOrNewLine();
cleenup();
return 1;
}
//CONNECTing
if ((connect(io.num, (struct sockaddr*)&server, sizeof(server))) == -1) {
cout << "ERROR! Client: connect() failed (socket number " + std::to_string(io.num) + "). " + getSocketErrorOrNewLine();
cleenup();
return 1;
}
}
提前感谢您的回答。
**UPDATE:**while()循环正在工作(但可能不是最佳)解决方案-测试API时存在错误。
1条答案
按热度按时间dbf7pr2w1#
正如你们中的许多人所写的,while循环是唯一的方法。我希望有一些“漂亮”的解决方案,但这也没关系。