Linux环境设置Socket接收和发送超时:
须如下定义:struct timeval timeout = {3,0};
//设置发送超时
setsockopt(socket,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(struct timeval));
//设置接收超时
setsockopt(socket,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout,sizeof(struct timeval));
另外常用的方式是使用select函数设置fd为读时间,并设置超时时间。
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <strings.h> #include <string.h> #include <thread> #include <unistd.h> extern char *optarg; extern int optind, opterr, optopt; #include <getopt.h> #define LOG_ERROR my_printf int my_printf(char *fmt, ...) { char buffer[1024]; va_list argptr; int length = 0; va_start(argptr, fmt); length = vsnprintf(buffer,1024 ,fmt, argptr); va_end(argptr); printf("%s\n", buffer); return (length + 1); } int start_client(const char *host, int port, const char *local_host = NULL) { int client_socket = socket(AF_INET,SOCK_STREAM,0); if( client_socket < 0) { LOG_ERROR("Create socket failed, errno %d", errno); return -1; } //设置一个socket地址结构server_addr,代表服务器的internet地址, 端口 struct sockaddr_in server_addr; bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family = AF_INET; if(inet_aton(host,&server_addr.sin_addr) == 0) { LOG_ERROR("Server address inet_aton failed, errno %d!", errno); return -1; } if (local_host != NULL) { sockaddr_in client_addr; client_addr.sin_family = AF_INET; client_addr.sin_addr.s_addr = inet_addr(local_host); if (bind(client_socket,(struct sockaddr*)&client_addr, sizeof(client_addr)) == -1) { LOG_ERROR("\nBind client failed, local_host %s, errno %d, %s\n", local_host, errno, strerror(errno)); close(client_socket); return -1; } } server_addr.sin_port = htons(port); socklen_t server_addr_length = sizeof(server_addr); //向服务器发起连接,连接成功后client_socket代表了客户机和服务器的一个socket连接 if(connect(client_socket,(struct sockaddr*)&server_addr, server_addr_length) < 0) { LOG_ERROR("Connect to %s:%d failed! error %d, %s", host, port, errno, strerror(errno)); close(client_socket); return -1; } // write(client_socket, "Hello Server", strlen("Hello Server")); return client_socket; } int main() { int sock = 0; struct timeval timeout = {3,0}; int tm = 0; int res = 0; char buf[1024]; sock = start_client("127.0.0.1", 5050); setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval)); tm = time(0); res = read(sock, buf, 1024); fprintf(stderr, "Read timeout %d\n", time(0) - tm); return 0; }