the Linux environment sets the socket receive and send timeouts: must be defined as follows : struct Timeval timeout = {3,0};
//Set Send timeout
setsockopt (Socket,sol_socket,so_sndtimeo, (char *) &timeout,sizeof (struct timeval)); //Set receive timeout
setsockopt (Socket,sol_socket,so_rcvtimeo, (char *) &timeout,sizeof (struct timeval));Another common way is to use the Select function to set FD to read time and set the time-out.
#include <sys/socket.h>#include<netinet/inch.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 intOptind, Opterr, optopt; #include<getopt.h>#defineLog_error my_printfintmy_printf (Char*FMT, ...) { Charbuffer[1024x768]; Va_list argptr; intLength =0; Va_start (Argptr, FMT); Length= vsnprintf (buffer,1024x768, FMT, argptr); Va_end (ARGPTR); printf ("%s\n", buffer); return(Length +1);}intStart_client (Const Char*host,intPortConst Char*local_host =NULL) { intClient_socket = socket (Af_inet,sock_stream,0); if(Client_socket <0) {Log_error ("Create socket failed, errno%d", errno); return-1; } //set a socket address structure server_addr, which represents the server's Internet address, Port structsockaddr_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, (structsockaddr*) &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); //initiate a connection to the server, Client_socket represents a socket connection for the client and the server after the connection is successful if(Connect (Client_socket,structsockaddr*) &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")); returnClient_socket;}intMain () {intSock =0; structTimeval Timeout = {3,0}; intTM =0; intres =0; Charbuf[1024x768]; Sock= Start_client ("127.0.0.1",5050); setsockopt (sock, Sol_socket, So_rcvtimeo, (Char*) &timeout,sizeof(structtimeval)); TM= Time (0); Res= Read (sock, buf,1024x768); fprintf (stderr,"Read Timeout%d\n", Time (0) -TM); return 0;}
One way to set the socket receive and send timeout