使用套接字,我不知道如何设置超时?
谢谢
int sock, connected, bytes_recieved;
char send_data [128] , recv_data[128];
SOCKADDR_IN server_addr,client_addr;
int sin_size;
int j = 0;
::socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(4000);
server_addr.sin_addr.s_addr = INADDR_ANY;
::bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
::listen(sock, 5);
::fflush(stdout);
while(1)
{
sin_size = sizeof(struct sockaddr_in);
connected = ::accept(sock, (struct sockaddr *)&client_addr, &sin_size);
while (1)
{
j++;
::send(connected, send_data, strlen(send_data), 0);
//dealing with lost communication ?
//and reastablishing communication
//set timeout and reset on timeout error
}
}
::closesocket(sock);
Run Code Online (Sandbox Code Playgroud) 是否存在超时交叉平台soulution以接受客户端使用accept功能而无需将套接字设置为非阻塞?
我知道我应该使用select它的功能,但我做错了什么?
SOCKET NativesAcceptClient(SOCKET s, int timeout)
{
int iResult;
struct timeval tv;
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(s, &rfds);
tv.tv_sec = (long)timeout;
tv.tv_usec = 0;
iResult = select(s, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
if(iResult > 0)
{
return accept(s, NULL, NULL);
}
else
{
//always here, even if i connect from another application
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何解决?谢谢!