我有一个客户端/服务器设置,我想我的客户端知道如果服务器已经接受连接。 否则,我的客户不知道它还在等待被接受。 我不能依靠进一步的沟通(协议规范)来validation这一点。 因此,例如从服务器向客户端发送“Good to go”string不是一个选项。 有没有一个标志或我可以检查,看看服务器是否确实收到的东西? 以下是一些示例代码:
/* Client */ ... getaddrinfo(ip, port, &hints, &servinfo); connect(sockfd, info->ai_addr, info->ai_addrlen); if (info == NULL) { printf("connection failure\n"); exit(1); } inet_ntop(info->ai_family, get_in_addr((struct sockaddr *)info->ai_addr), ipstring, sizeof(ipstring)); printf("Connected to %s!\n", ipstring); ... /* Server */ ... pause(); /* If don't accept the connection, how to make the client know? */ new_fd = accept(sockfd, (struct sockaddr *)&cli_addr, &addr_size); ...
由于积压,服务器可以在接受呼叫之前发送SYN-ACK。 所以客户端调用connect()
可以在服务器调用accept()
之前返回。
正如你所说:从服务器的“好去”消息是不可选的。 怎么样:来自客户端的“echo”请求。 所以服务器会在接受后回应。
如果TCP流中有任何额外的流量不是一个选项。 你可以使用辅助数据吗?
你应该检查来自connect()
的返回值,因为它会通过errno
来表示失败的原因。
你的情况下connect()
调用会超时,因此connect()
将返回-1
, errno
被设置为ETIMEDOUT
int ret = connect(sockfd, info->ai_addr, info->ai_addrlen); if (ret == -1) { /* connect failed */ switch(errno) { case ETIMEDOUT: /* your server didn't accept the connection */ case ECONNREFUSED: /* your server isn't listening yet, eg didn't start */ default: /* any other error, see man 2 connect */ } }