poll服务器模型

Posted 药剂学徒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poll服务器模型相关的知识,希望对你有一定的参考价值。

#include<stdio.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<poll.h>
#include<errno.h>
#include<string.h>

#define buflen 1024
#define port 8888
#define openmax 1024
#define backlog 10
int main(int argc,char *argv[]){
	int listenfd = socket(AF_INET,SOCK_STREAM,0);
	struct sockaddr_in servaddr;
	bzero(&servaddr,sizeof(&servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	int ret = bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
	ret = listen(listenfd,backlog);
	struct pollfd client[openmax];
	int i =0;
	for(i = 0;i<openmax;i++){
			client[i].fd = -1;
	}
	client[0].fd = listenfd;
	client[0].events = POLLIN;
	int maxi = 0;
	int len ;
	int nready ;
	int connfd,sockfd;
	struct sockaddr_in clientaddr;
	socklen_t client_len  = sizeof(clientaddr);
	char buf[buflen];
	char str[buflen];
	while(1){
		nready = poll(client ,maxi+1,-1);

		if(client[0].revents & POLLIN){
		connfd = accept(listenfd,(struct sockaddr*)&clientaddr,&client_len);
		printf("received form %s \t at port %d\n",inet_ntop(AF_INET,&clientaddr.sin_addr,str,sizeof(str)),ntohs(clientaddr.sin_port));
		

		for(int i = 1;i<openmax;i++){
			if(client[i].fd<0){
				client[i].fd = connfd;
				break;
			}
		}

		client[i].events = POLLIN;

		if(i>maxi){
			maxi = i;
		}

		if(--nready <= 0){
			continue;
		}
		}
		for(i = 1;i<maxi;i++){
			sockfd = client[i].fd ;
			if(sockfd<0){
				continue;
			}
			
			len = read(sockfd,buf,buflen);
			if(len<=0){
				printf("CLOSE connection \n");
				close(sockfd);
				client[i].fd = -1;
			}
			else{
				int k ;
				for(k = 0;k<len;k++){
					buf[k] = toupper(buf[k]);
				}
				write(sockfd,buf,buflen);
			}
			if(--nready <= 0){
				break;
			}
		}
	}
	return 0;
}

  服务端

#include<stdio.h>
#include<sys/socket.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<stdlib.h>

#define port 8888
#define buflen 1024
int main(int argc,char* argv[]){
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	int len ;
	if(sockfd<0){
		printf("socket failed\n");
		exit(1);
	}
	char recvbuf[buflen];

	struct sockaddr_in serv_addr;
	bzero(&serv_addr,sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(port);
	inet_pton(AF_INET,"127.0.0.1",&serv_addr.sin_addr);

	int ret = connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
	printf("start to connect...\n");
	while(fgets(recvbuf,sizeof(recvbuf),stdin)!=NULL){
		write(sockfd,recvbuf,strlen(recvbuf));
		len = read(sockfd,recvbuf,sizeof(recvbuf));
		write(STDOUT_FILENO,recvbuf,len);
	}
	return 0;
}

  客户端

以上是关于poll服务器模型的主要内容,如果未能解决你的问题,请参考以下文章

多路IO复用模型--select, poll, epoll

五种高阶IO模型以及多路转接技术(selectpoll和epoll)及其代码验证

五种高阶IO模型以及多路转接技术(selectpoll和epoll)及其代码验证

五种高阶IO模型以及多路转接技术(selectpoll和epoll)及其代码验证

理解网络IO模型

32网络通信之Poll模型