select和poll

slelect实现客户端

#include 
#define PORT 8888
#define PORT1 9999
#define IP   "192.168.125.147"
int main(int argc, const char *argv[])
{
	int cfd=-1;
	if((cfd=socket(AF_INET,SOCK_STREAM,0))==-1)
	{
		perror("socket error");
		return -1;
	}	
	int reuse=1;
	if(setsockopt(cfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
	{
		perror("setsockopt error");
		return-1;
	}
	struct sockaddr_in cin;
	cin.sin_family=AF_INET;
	cin.sin_port=htons(PORT1);
	cin.sin_addr.s_addr=inet_addr(IP);
	if(bind(cfd,(struct sockaddr*)&cin,sizeof(cin))==-1)
	{
		perror("bind error");
		return -1;
	}
	struct sockaddr_in sin;
	sin.sin_family=AF_INET;
	sin.sin_port=htons(PORT);
	sin.sin_addr.s_addr=inet_addr(IP);
	if(connect(cfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
	{
		perror("connect error");
		return -1;
	}
	char buf[128]="";
	char rbuf[128]="";
	fd_set readfds,temp;
	FD_ZERO(&readfds);
	FD_SET(0,&readfds);
	FD_SET(cfd,&readfds);
	while(1)
	{
		temp=readfds;
		if(select(cfd+1,&temp,NULL,NULL,NULL)==-1)
		{
			perror("select error");
			return -1;
		}
		if(FD_ISSET(0,&temp))
		{
			bzero(buf,128);
			scanf("%s",buf);
			if(strcmp(buf,"quit")==0)
			{
				puts("退出");
				break;
			}
			send(cfd,buf,sizeof(buf),0);
		}
		if(FD_ISSET(cfd,&temp))
		{
			bzero(rbuf,128);
			recv(cfd,rbuf,sizeof(rbuf),0);
			printf("服务器:%s\n",rbuf);
		}
	}
	close(cfd);
	return 0;
}

select和poll_第1张图片

poll实现服务器

ubuntu@ubuntu:day5$ cat 5.poll.c 
#include 
#define PORT 8888
#define IP "192.168.125.147"
int main(int argc, const char *argv[])
{
	int sfd=-1;
	if((sfd=socket(AF_INET,SOCK_STREAM,0))==-1)
	{
		perror("socket error");
		return -1;
	}
	int reuse=1;
	if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
	{
		perror("setsockopt error");
		return-1;
	}
	struct sockaddr_in sin;
	sin.sin_family=AF_INET;
	sin.sin_port=htons(PORT);
	sin.sin_addr.s_addr=inet_addr(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 len=sizeof(cin);
	struct sockaddr_in sock[1024];
	char ok[50];
	int newfd=-1;
	int maxfd=4;
	struct pollfd fds[1024];
	fds[0].fd=0;
	fds[0].events=POLLIN;
	fds[1].fd=sfd;
	fds[1].events=POLLIN;
	int count=2;
	puts("准备就绪");
	while(1)
	{
		if(poll(fds,count,-1)==-1)
		{
			perror("poll error");
			return -1;
		}
		for(int i=0;i

select和poll_第2张图片

你可能感兴趣的:(c语言)