#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>
#define MAXFD 10
int create_socket();
void fds_init(struct pollfd fds[])
{
int i = 0;
for( ; i < MAXFD; i++)
{
fds[i].fd = -1;
fds[i].events = 0;
fds[i].revents = 0;
}
}
void fds_add(struct pollfd fds[], int fd)
{
int i = 0;
for( ; i < MAXFD; i++)
{
if( fds[i].fd == -1) //目前只有数组的第一个位置是有值的
{
fds[i].fd = fd;
fds[i].events = POLLIN;
fds[i].revents = 0;
break;
}
}
}
void fds_del(struct pollfd fds[], int fd)
{
int i = 0;
for( ; i < MAXFD; i++)
{
if( fds[i].fd == -1)
{
fds[i].fd = fd;
fds[i].events = 0;
fds[i].revents = 0;
break;
}
}
}
int main()
{
int sockfd = create_socket():
assert( sockfd != -1);
struct pollfd fds[MAXFD];
fds_init(fds);
fds_add(fds,sockfd);
while(1)
{
int n = poll(fds,MAXFD,5000);
if( n == -1)
{
perror("pll error");
}
else if( n == 0)
{
printf("time out\n!");
}
else
{
int i = 0;
for( ; i < MAXFD; i++)
{
if( fds[i].fd == -1)
{
continue;
}
if( fds[i].revents & POLLRDHUP )
{
//处理描述符的读事件
if( fds[i].revents & POLLIN)
{
//监听套接字
if( fds[i].fd == sockfd)
{
//处理 如果是文件描述符的话
struct sockaddr_in cli;
int len = sizeof(cli);
int c = accept(sockfd, (struct sockaddr*)&cli, &len);
if( c < 0)
{
printf("clien link error\n");
continue;
printf("accept c = %d\n", c);
fds_add(fds, c);
}
}
else
{
//recv
char buff[128] = {0};
int num = recv(fds[i],fd,buff,127,0);
if ( num <= 0)
{
close(fd);
fds_del(fds, fds[i], fd);
printf("one client over\n");
}
}
}
}
}
}
}
int create_socket()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if( sockfd == -1)
{
return -1;
}
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_familiy = AF_INET;
saddr.sin_port = htons(6000);
saddr.sin_addr.sin_addr = inet_addr("127.0.0.1");
int res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
assert( res != -1);
listen(sockfd,5);
}