#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/poll.h>
#include<unistd.h>
#include<stdio.h>
#define FD_SIZE 1024
struct pollfd fds[FD_SIZE];
int fd_num = 0;
int add(int fd,short events)
{
int i=0;
for(;i<FD_SIZE;++i)
{
if(0==fds[i].fd)
{
fds[i].fd = fd;
fds[i].events = events;
++fd_num;
return 0;
}
}
return -1;
}
int clr(int fd)
{
int i=0;
for(;i<FD_SIZE;++i)
{
if(fds[i].fd==fd)
{
fds[i].fd = 0;
fds[i].events = 0;
--fd_num;
}
}
}
void main()
{
memset(fds,0,sizeof(fds));
int sock = socket(AF_INET,SOCK_STREAM,0);
if(-1==sock)
{
perror("create socket failed");
return;
}
int reuse = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(3000);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
if(bind(sock,(struct sockaddr*)&sin,sizeof(sin))<0)
{
perror("bind failed");
return;
}
listen(sock,5);
add(sock,POLLIN);
while(1)
{
struct pollfd temp_fds[FD_SIZE];
memcpy(&temp_fds,&fds,sizeof(fds));
int ret = poll(&temp_fds,fd_num,100000);
if(ret<0) break;
else if(ret==0)
{
continue;
}
int i=0;
for(;i<FD_SIZE;++i)
{
if(temp_fds[i].fd == sock && (temp_fds[i].revents & POLLIN))
{
struct sockaddr_in client_addr;
int sockaddr_len = sizeof(client_addr);
int fd = accept(sock,&client_addr,&sockaddr_len);
add(fd,POLLIN);
printf("accept new conn\n");
}
else if(temp_fds[i].revents & POLLIN)
{
char buf[100];
memset(buf,0,sizeof(buf));
recv(temp_fds[i].fd,buf,100,0);
printf("recv data:%s\n",buf);
}
}
}
}
#include<sys/socket.h>
#include<sys/poll.h>
#include<unistd.h>
#include<stdio.h>
#define FD_SIZE 1024
struct pollfd fds[FD_SIZE];
int fd_num = 0;
int add(int fd,short events)
{
int i=0;
for(;i<FD_SIZE;++i)
{
if(0==fds[i].fd)
{
fds[i].fd = fd;
fds[i].events = events;
++fd_num;
return 0;
}
}
return -1;
}
int clr(int fd)
{
int i=0;
for(;i<FD_SIZE;++i)
{
if(fds[i].fd==fd)
{
fds[i].fd = 0;
fds[i].events = 0;
--fd_num;
}
}
}
void main()
{
memset(fds,0,sizeof(fds));
int sock = socket(AF_INET,SOCK_STREAM,0);
if(-1==sock)
{
perror("create socket failed");
return;
}
int reuse = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(3000);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
if(bind(sock,(struct sockaddr*)&sin,sizeof(sin))<0)
{
perror("bind failed");
return;
}
listen(sock,5);
add(sock,POLLIN);
while(1)
{
struct pollfd temp_fds[FD_SIZE];
memcpy(&temp_fds,&fds,sizeof(fds));
int ret = poll(&temp_fds,fd_num,100000);
if(ret<0) break;
else if(ret==0)
{
continue;
}
int i=0;
for(;i<FD_SIZE;++i)
{
if(temp_fds[i].fd == sock && (temp_fds[i].revents & POLLIN))
{
struct sockaddr_in client_addr;
int sockaddr_len = sizeof(client_addr);
int fd = accept(sock,&client_addr,&sockaddr_len);
add(fd,POLLIN);
printf("accept new conn\n");
}
else if(temp_fds[i].revents & POLLIN)
{
char buf[100];
memset(buf,0,sizeof(buf));
recv(temp_fds[i].fd,buf,100,0);
printf("recv data:%s\n",buf);
}
}
}
}