网络编程 day5

    TCP客户端IO复用select函数实现

#include 
#define SER_PORT 8888
#define SER_IP "192.168.125.11"
int main(int argc, const char *argv[])
{
	int sfd=socket(AF_INET,SOCK_STREAM,0);
	if(sfd==-1)
	{
		perror("");
		return -1;
	}
 
	struct sockaddr_in rin;
	rin.sin_family=AF_INET;
	rin.sin_port=htons(SER_PORT);
	rin.sin_addr.s_addr=inet_addr(SER_IP);
	
	if(connect(sfd,(struct sockaddr*)&rin,sizeof(rin))==-1)
	{
		perror("connect error");
		return -1;
	}
	
	fd_set readfds,tempfds;
	FD_ZERO(&readfds);
	FD_SET(0,&readfds);
	FD_SET(sfd,&readfds);
	int maxfd=sfd;
	
	while(1)
	{
		tempfds=readfds;
		int res=select(maxfd+1,&tempfds,NULL,NULL,NULL);
		if(res==-1)
		{
			perror("");
			return -1;
		}
		else if(res==0)
		{
			printf("manba out\n");
			return -1;
		}
		for(int i=0;i<=maxfd;i++)
		{
			if(!FD_ISSET(i,&tempfds))
			{
				continue;
			}
			if(i==0)
			{
				char buf[128];
				scanf("%s",buf);
				send(sfd,buf,sizeof(buf),0);
			}
			else if(i==sfd)
			{
				char buf[128]="";
				int res=recv(sfd,buf,sizeof(buf),0);
				printf("%d\n",res);
				printf("收到的消息为:%s\n",buf);
			}
		}
 
	}
	close(sfd);
	return 0;
}

 TCP并发服务器的IO复用poll函数实现

#include 
#define SER_PORT 8888
#define SER_IP "192.168.125.11"
int main(int argc, const char *argv[])
{
	int sfd=socket(AF_INET,SOCK_STREAM,0);
	if(sfd==-1)
	{
		perror("sfd error:");
		return -1;
	}
	int reuse=1;
	if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
	{
		perror("");
		return -1;
	}
 
	struct sockaddr_in sin;
	sin.sin_family=AF_INET;
	sin.sin_port=htons(SER_PORT);
	sin.sin_addr.s_addr=inet_addr(SER_IP);
	if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
	{
		perror("bind error:");
		return -1;
	}
 
	if(listen(sfd,128)==-1)
	{
		perror("listen error:");
		return -1;
	}
 
	struct sockaddr_in cin;
	socklen_t socklen=sizeof(cin);
	int newfd=-1;
	int n=2;
	struct pollfd pfd[1024];
	pfd[0].fd=sfd;
	pfd[0].events=POLLIN;
	pfd[1].fd=0;
	pfd[1].events=POLLIN;
	
	struct sockaddr_in cin_arr[1024];
		
 
	while(1)
	{
		int res=poll(pfd,n,-1);
		if(res==-1)
		{
			perror("select error:");
			return -1;
		}
		else if(res==0)
		{
			printf("time out\n");
			return -1;
		}
 
 
			if(pfd[0].revents==POLLIN)
			{
				newfd=accept(sfd,(struct sockaddr*)&cin,&socklen);
				if(newfd==-1)
				{
					perror("newfd error:");
					return -1;
				}
				printf("[%s:%d:%d]发来链接请求\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);
 
				n++;
				pfd[n-1].fd=newfd;
				pfd[n-1].events=POLLIN;
				cin_arr[newfd]=cin;
 
			}
 
			if(pfd[1].revents==POLLIN)
			{
				char buf[128]="";
				scanf("%s",buf);
				for(int i=4;i

你可能感兴趣的:(嵌入式学习-网络编程,网络,linux,c语言)