socket网络编程-----I/O复用之poll函数

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/poll.h>
#include <sys/time.h> #define BUFSIZE 255 int rw_opt(int rdfd,int wdfd)
{
int num;
char buf[BUFSIZE];
memset(buf,,sizeof(buf));
num = read(rdfd,buf,sizeof(buf));
if(wdfd == )
write(,">>>",);
write(wdfd,buf,num);
if(strncmp(buf,"quit",) == )
return ;
return num;
} int main()
{
int sockfd,ret;
int acceptfd;
struct sockaddr_in s_addr;
sockfd = socket(AF_INET,SOCK_STREAM,);
if(sockfd == -)
{
printf("socket error!\n");
return ;
} memset(&s_addr,,sizeof(struct sockaddr_in));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons();
s_addr.sin_addr.s_addr = htons(INADDR_ANY);
ret = bind(sockfd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));
if(ret == -)
{
printf("bind error!\n");
return ;
} ret = listen(sockfd,);
if(ret == -)
{
printf("listen error!\n");
return ;
} int addrlen = sizeof(struct sockaddr);
acceptfd = accept(sockfd,(struct sockaddr *)&s_addr,&addrlen);
if(acceptfd == -)
{
printf("accept error!\n");
}
else
{
printf("%s-----%d\n",inet_ntoa(s_addr.sin_addr),ntohs(s_addr.sin_port));
} struct pollfd fds[];
fds[].fd=;
fds[].fd=acceptfd;
fds[].events=POLLIN|POLLOUT;
fds[].events=POLLIN|POLLOUT;
while()
{
ret=poll(fds, , -);
if(ret<)
{
perror("poll");
continue;
}
if(fds[].revents&POLLIN)
{
ret=rw_opt(, acceptfd);
if(ret == )
break;
}
if(fds[].revents&POLLIN)
{
ret=rw_opt(acceptfd, );
if(ret == )
break;
}
}
close(acceptfd);
close(sockfd);
return ;
}

ser.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/poll.h>
#include <sys/time.h> #define BUFSIZE 255 int rw_opt(int rdfd,int wdfd)
{
int num;
char buf[BUFSIZE];
memset(buf,,sizeof(buf));
num = read(rdfd,buf,sizeof(buf));
if(wdfd == )
write(,">>>",);
write(wdfd,buf,num);
if(strncmp(buf,"quit",) == )
return ;
return num;
} int main(int argc,char **argv)
{
int sockfd,ret;
int acceptfd;
struct sockaddr_in s_addr;
sockfd = socket(AF_INET,SOCK_STREAM,);
if(sockfd == -)
{
printf("socket error!\n");
return ;
} memset(&s_addr,,sizeof(struct sockaddr_in));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons();
s_addr.sin_addr.s_addr = inet_addr(argv[]);
ret = connect(sockfd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));
if(ret == -)
{
printf("connect error!\n");
return ;
} struct pollfd fds[];
fds[].fd=;
fds[].fd=sockfd;
fds[].events=POLLIN|POLLOUT;
fds[].events=POLLIN|POLLOUT; while()
{
ret=poll(fds, , -);
if(ret<)
{
perror("poll");
continue;
}
if(fds[].revents&POLLIN)
{
ret=rw_opt(,sockfd);
if(ret == )
break;
}
if(fds[].revents&POLLIN)
{
ret=rw_opt(sockfd, );
if(ret == )
break;
}
}
close(sockfd);
return ;
}

cli.c

上一篇:基于jquery上的轻量级《数据模板解析》插件


下一篇:(五)Cluster Health