#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <poll.h>
#define max_listen 5
int main()
{
int fd[1024] = {0};
int sfd = socket(AF_INET , SOCK_STREAM, 0 );
if(sfd == -1)
{
printf(“create sock err\n”);
return 0;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = 1203;
addr.sin_addr.s_addr = inet_addr (“127.0.0.1”);
int ret = bind(sfd , (struct sockaddr*)&addr, sizeof(addr));
if(-1 == ret)
{
printf("bind error\n");
perror("bind");
return 0;
}
ret = listen (sfd , max_listen);
if(-1 == ret)
{
printf("listen error \n");
return 0;
}
struct pollfd fds[10];
for(int i = 0 ; i < 10 ; i++)
{
fds[i].fd = -1;
fds[i].events = POLLIN;
}
fds[0].fd = sfd ;
int maxfd = 0;
struct sockaddr_in cl_addr;
socklen_t tlen = sizeof (cl_addr);
while (1)
{
printf("wait_poll\n");
ret = poll(fds, maxfd + 1, -1);
printf("--------------\n");
if(ret == -1)
{
perror("poll");
exit(0);
}
if(fds[0].revents & POLLIN)
{
fds[0].revents = 0;
int t =0;
for(t = 0 ; t < 1024; t++)
{
if(fds[t].fd == -1)
break;
}
printf("you lianjie\n");
fds[t].fd = accept (sfd, (struct sockaddr*)&cl_addr, &tlen);
char ip[24] = {0};
printf("IP: %s, port: %d\n",
inet_ntop(AF_INET, &cl_addr.sin_addr.s_addr, ip, sizeof(ip)),
cl_addr.sin_port);
maxfd = t > maxfd ? t : maxfd;
printf("maxfd: %d \n",maxfd);
}
else
{
for(int j = 1 ; j < maxfd + 1; j++)
{
if(fds[j].revents & POLLIN)
{
fds[j].revents = 0;
char buf[1024];
int res = read (fds[j].fd, buf, sizeof(buf));
if(res == -1)
{
perror("recv");
}
else if(res == 0)
{
printf("%d client sock is closed\n",fds[j].fd);
close(fds[j].fd);
fds[j].fd = -1;
}
else
{
printf("%d msg len: %d %s\n",fds[j].fd, res, buf);
}
break;
}
}
}
}
exit(1);
}