Linux:封装readline按行读取

/ Linux / 没有评论 / 467浏览

相比较上一篇文章,我们是利用自定义包体,避免粘包。这篇源码是利用'\n',在套接口中读取数据遇到'\n',就算读取一条数据。

封装了一下readline函数

在接收的数据中,我们要判断'\n',这里我们采取“偷窥”的方式,不然一个字节一个字节判断,太麻烦。"偷窥":利用recv函数能接收到缓存区的数据,然后查看有没有'\n'.recv函数只能使用在套接口中。  

客户端代码:

  /*
readline 实现,遇到\n 就算作是一条消息,可以解决粘包问题(遇到\r\n,在包尾,ftp协议就是这么做的)
*/
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#define ERR_EXIT(m)do{perror(m);exit(EXIT_FAILURE);}while(0)

ssize_t readn(int fd, void *buf, size_t count)
{
	size_t nleft = count;//剩余的字节数
	size_t nread;//接收的字节数 
	char * bufp = (char *)buf;
	while(nleft > 0)
	{
		if((nread = read(fd,bufp,nleft)) < 0)
		{
			if(errno == EINTR)//信号中断
				continue;
			return -1;
		}
		else if(nread == 0) //客户端关闭了
		{
			return count - nleft;
		}
		bufp += nread;
		nleft -=nread;
	}
	return count;
}

ssize_t writen(int fd, const void *buf, size_t count)
{
	size_t nleft = count;//剩余的字节数
	size_t nwritten;//接收的字节数 
	char * bufp = (char *)buf;
	while(nleft > 0)
	{
		if((nwritten = write(fd,bufp,nleft)) < 0)
		{
			if(errno == EINTR)//信号中断
				continue;
			return -1;
		}
		else if(nwritten == 0) //客户端关闭了
		{
			continue;
		}
		bufp += nwritten;
		nleft -=nwritten;
	}
	return count;
}

//MSG_PEEK 只是从缓存区接收到buf,但是未清除掉套接口缓存区数据
ssize_t recv_peek(int sockfd, void *buf, size_t len)
{
	while(1)
	{
		int ret = recv(sockfd,buf,len,MSG_PEEK);
		if(ret == -1 && errno == EINTR)
		{
			continue;
		}
		return ret;
	}
}

ssize_t readline(int sockfd,void *buf,size_t maxline)
{
	int ret;
	int nread;//接收到的字节数
	char * bufp = buf;
	int nleft = maxline;
	while(1)
	{
		ret = recv_peek(sockfd,bufp,nleft);
		if(ret <0)
			return ret;
		else if(ret == 0)
			return ret;
		nread = ret;
		int i;
		for(i = 0;i<nread;i++)
		{
			if(bufp[i] == '\n')
			{
				ret = readn(sockfd,bufp,i+1);
				if(ret != i+1)
				{
					exit(EXIT_FAILURE);
				}
				return ret;
			}
		}
		if(nread > nleft)
		{
			exit(EXIT_FAILURE);
		}
		nleft -= nread;
		ret = readn(sockfd,bufp,nread);
		if(ret != nread)
		{
			exit(EXIT_FAILURE);
		}
		bufp += nread; //放在后面
		
	}
	return -1;
}

int main(void)
{
	int sock;
	if((sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) <0)
	{
		ERR_EXIT("socket");
	}
	struct sockaddr_in servaddr;
	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(5188);

    //servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    //inet_aton("127.0.0.1",&servaddr.sin_addr);
	
	if(connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr)) < 0)
	{
       ERR_EXIT("connect");
	}

	char sendbuf[1024] = {0};
	char recvbuf[1024] = {0};
	while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL)
	{
		writen(sock,sendbuf,strlen(sendbuf));

		//readn(sock,recvbuf,sizeof(recvbuf));
		int ret =readline(sock,recvbuf,sizeof(recvbuf));
		if(ret == -1)
		{
			ERR_EXIT("read");
		}
		else if(ret == 0)//客户端关闭
		{
			printf("client close\n");
			break;
		}
	
		fputs(recvbuf,stdout);
		memset(sendbuf,0,sizeof(sendbuf));
		memset(recvbuf,0,sizeof(recvbuf));
		
	}
	close(sock);
    return 0;
}

服务端代码:

/*
readline 实现,遇到\n 就算作是一条消息,可以解决粘包问题(遇到\r\n,在包尾,ftp协议就是这么做的)
*/

#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#define ERR_EXIT(m)do{perror(m);exit(EXIT_FAILURE);}while(0)

ssize_t readn(int fd, void *buf, size_t count)
{
	size_t nleft = count;//剩余的字节数
	size_t nread;//接收的字节数 
	char * bufp = (char *)buf;
	while(nleft > 0)
	{
		if((nread = read(fd,bufp,nleft)) < 0)
		{
			if(errno == EINTR)//信号中断
				continue;
			return -1;
		}
		else if(nread == 0) //客户端关闭了
		{
			return count - nleft;
		}
		bufp += nread;
		nleft -=nread;
	}
	return count;
}

ssize_t writen(int fd, const void *buf, size_t count)
{
	size_t nleft = count;//剩余的字节数
	size_t nwritten;//接收的字节数 
	char * bufp = (char *)buf;
	while(nleft > 0)
	{
		if((nwritten = write(fd,bufp,nleft)) < 0)
		{
			if(errno == EINTR)//信号中断
				continue;
			return -1;
		}
		else if(nwritten == 0) //客户端关闭了
		{
			continue;
		}
		bufp += nwritten;
		nleft -=nwritten;
	}
	return count;
}

//MSG_PEEK 只是从缓存区接收到buf,但是未清除掉套接口缓存区数据
ssize_t recv_peek(int sockfd, void *buf, size_t len)
{
	while(1)
	{
		int ret = recv(sockfd,buf,len,MSG_PEEK);
		if(ret == -1 && errno == EINTR)
		{
			continue;
		}
		return ret;
	}
}

ssize_t readline(int sockfd,void *buf,size_t maxline)
{
	int ret;
	int nread;//接收到的字节数
	char * bufp = buf;
	int nleft = maxline;
	while(1)
	{
		ret = recv_peek(sockfd,bufp,nleft);
		if(ret <0)
			return ret;
		else if(ret == 0)
			return ret;
		nread = ret;
		int i;
		for(i = 0;i<nread;i++)
		{
			if(bufp[i] == '\n')
			{
				ret = readn(sockfd,bufp,i+1);
				if(ret != i+1)
				{
					exit(EXIT_FAILURE);
				}
				return ret;
			}
		}
		if(nread > nleft)
		{
			exit(EXIT_FAILURE);
		}
		nleft -= nread;
		ret = readn(sockfd,bufp,nread);
		if(ret != nread)
		{
			exit(EXIT_FAILURE);
		}
		bufp += nread; //放在后面
		
	}
	return -1;
}

//多个客户端可以连接,将accept弄作一个进程,读取发送数据是一个进程
void do_service(int conn)
{
	char recvbuf[1024];
	while(1)
	{
        memset(&recvbuf,0,sizeof(recvbuf));
		int ret = readline(conn,recvbuf,1024);//接收包头
		if(ret == -1)
		{
			ERR_EXIT("readline");
		}
		if(ret == 0)
		{
			printf("client close\n");
			break;
		}
		fputs(recvbuf,stdout);
		writen(conn,&recvbuf,strlen(recvbuf));
	}
}

int main(void)
{
	int listenfd;
	if((listenfd = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) <0)
		//listenfd = socket(PF_INET,SOCK_STREAM,0);
	{
		ERR_EXIT("socket");
	}
	struct sockaddr_in servaddr;
	memset(&servaddr,0,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(5188);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    //servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    //inet_aton("127.0.0.1",&servaddr.sin_addr);
	
	//开启地址重复利用(在TIME_WAIT未消失的情况下,允许服务器重启)
	int on = 1;
	if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)) < 0)
		ERR_EXIT("setsockopt");

	if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) < 0)
		ERR_EXIT("bind");
    
    if(listen(listenfd,SOMAXCONN) < 0)
		ERR_EXIT("listen");
	
	struct sockaddr_in peeraddr;
	socklen_t peerlen = sizeof(peeraddr);
	
	int conn;
	pid_t pid;
	while(1)
	{
		if((conn = accept(listenfd,(struct sockaddr*)&peeraddr, &peerlen)) < 0)
			ERR_EXIT("accept");
		printf("ip=%s port=%d\n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port));
		pid = fork();
		if(pid == -1)
			ERR_EXIT("fork");
		if(pid == 0)
		{
			close(listenfd);
			do_service(conn);
			exit(EXIT_SUCCESS);
		}
		else
		{
			close(conn);
		}
	}

    return 0;
}