linux 下tcp 客户端读取数据

以下代码为linux下使用tcp协议读取客户端发送的数据代码:

#include   
#include   
#include   
#include  
#include 
#include   
#include   
#include   
  
#define MAXLINE 80  
#define SERV_PORT 2111  

char sendline[32] ={0x2,0x73,0x45,0x4e,0x20,0x4c,0x4d,0x44,0x73,0x63,0x61,0x6e,0x64,0x61,0x74,0x61,0x20,0x31,0x3};


int selectlidar( int fd, int sec, int usec)
{
	int ret;
	fd_set fds;
	struct timeval timeout;

	timeout.tv_sec = sec;
	timeout.tv_usec = usec;

	FD_ZERO(&fds); //每次循环都要清空集合,否则不能检测描述符变化
	FD_SET(fd,&fds); //添加描述符

	ret = select(fd+1,&fds,&fds,NULL,&timeout);
	if(0 > ret)
	{
		printf("lidar recv select error\n");
        	return -1;	
	}
	else if (ret == 0)
	{
	        printf("uart read select timeout\n");
	        return 0;
	}
    	else {
		if(FD_ISSET(fd,&fds)) //测试sock是否可读,即是否网络上有数据
		{
			return 1;

		}
		else
		{
			return 0;
		}
    	}
	

}

int main(int argc, char *argv[])  
{  
    struct sockaddr_in servaddr;  
    char buf[MAXLINE];  
  
    socklen_t cliaddr_len; 
    int sockfd, n,connfd,ret;  
    char recvline[MAXLINE];  
  
    sockfd = socket(AF_INET, SOCK_STREAM, 0);  
    bzero(&servaddr, sizeof(servaddr));  
    servaddr.sin_family = AF_INET;   
    servaddr.sin_addr.s_addr = inet_addr("192.168.0.1");
    servaddr.sin_port = htons(SERV_PORT);  
    
    connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));  
 
    if(send(sockfd,sendline,strlen(sendline),0) < 0)
    {
    	printf("send mes error:%s errno: %d",strerror(errno),errno);
    	exit(0);
    }
   
    while(1)
    {	
	
	ret = selectlidar(sockfd,1,0);
	if(ret > 0)
	{
		n = recv(sockfd, buf, MAXLINE,0);
		buf[n]='\0';
		printf("recv msg from client:%s\n",buf);
			
	}

    }
    	
    close(sockfd);  
    return 0;  
}  

你可能感兴趣的:(linux)