linux 非阻塞Tcp客户端

时间:2024-01-26 16:33:28
/**********************************************************************
* 函数名称: 建立读取H264视频TCP客户端
* 功能描述: 通过TCPClient发送"aaa"与TcpSERVER端建立连接
* 输入参数: addr    TCPserver端的IP地址
       port    TCPserver端的端口 * 输出参数: handle 建立连接后的SOCKET句柄地址 * 返 回 值:0为成功,1为失败 * 其它说明: **********************************************************************
*/ int RecvH264Client(const char* addr, int port, int *handle ) { int sockfd, recvbytes, res, flags, error, n; socklen_t len; fd_set rset, wset; struct timeval tval; tval.tv_sec = 0; tval.tv_usec = 300000; struct sockaddr_in serv_addr; char *sendData = "aaa"; /* 发送字符串 */ char buf[1024] = {0}; /* 接收buffer */ /* 创建socket描述符 */ if ( (sockfd = socket( AF_INET, SOCK_STREAM, 0 ) ) == -1 ) { LOGI( "socket create failed" ); return(1); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons( port ); serv_addr.sin_addr.s_addr = inet_addr( addr ); bzero( &(serv_addr.sin_zero), 8 ); flags = fcntl( sockfd, F_GETFL, 0 ); fcntl( sockfd, F_SETFL, flags | O_NONBLOCK ); /* 设置为非阻塞 */ if ( (res = connect( sockfd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr) ) ) < 0 ) { if ( errno != EINPROGRESS ) { return(1); } } /* 如果server与client在同一主机上,有些环境socket设为非阻塞会返回 0 */ if ( 0 == res ) goto done; FD_ZERO( &rset ); FD_SET( sockfd, &rset ); wset = rset; if ( (res = select( sockfd + 1, NULL, &wset, NULL, &tval ) ) <= 0 ) { LOGI( "connect time out\n" ); close( sockfd ); return(-1); }else { len = sizeof(error); getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &len ); if ( error ) { LOGI( stderr, "Error in connection() %d - %s\n", error, strerror( error ) ); return(1); } } done: if ( (n = send( sockfd, sendData, strlen( sendData ), 0 ) ) == -1 ) { LOGI( "send error!" ); close( sockfd ); return(1); } if ( (n = select( sockfd + 1, &rset, NULL, NULL, &tval ) ) <= 0 ) /* rset没有使用过,不用重新置为sockfd */ { LOGI( "receive time out or connect error" ); close( sockfd ); return(1); } if ( (recvbytes = recv( sockfd, buf, 1024, 0 ) ) == -1 ) { LOGI( "recv error!" ); close( sockfd ); return(1); } LOGI( "receive num %s\n", buf ); *handle = sockfd; return(0); }