使用select io复用实现超时设置

时间:2021-01-15 15:49:35

在linux的socket编程中,经常会遇到超时设置的问题,例如请求方如果在Ks内不发送数据则服务器要断开连接停止服务。这里我使用select的io复用实现超时5s设置,具体代码片段如下:

fd_set fs;
timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
FD_ZERO(&fs);
FD_SET(socket_fd,&fs);
int ret = select(socket_fd+1,&fs,NULL,NULL,&tv);
if(ret == -1){
fprintf(stderr, "socket_job:run:error.\n");
}else if(ret == 0){
fprintf(stderr, "socket_job:run:time out.\n");
}else{
if(FD_ISSET(socket_fd,&fs)){
int length = 1024*1024;
char* buffer = new char[length];
memset(buffer,0,sizeof(char)*length);
int n = recv(socket_fd,buffer,sizeof(char)*length,0);
if(n > 0){
//deal msg
buffer[length] = '\0';
search_collector* searcher = new search_collector();
string result("");
searcher->search(buffer,10,result);
//send result,result must be end with \n
int result_length = strlen(result.c_str());
ret = send(socket_fd,result.c_str(),result_length,0);
int all_send = 0;
while(ret > 0 && ret < result_length){
result_length -= ret;
all_send += ret;
ret = send(socket_fd,result.c_str()+all_send,result_length,0);
}
}
delete[] buffer;
} }