#include<myhead.h>
#include<poll.h>
#define SERIP "192.168.0.138"
#define SERPORT 7890
#define CLIENTSIZE 6
int main(int argc, const char *argv[])
{
int oldfd=socket(AF_INET,SOCK_STREAM,0);
if(oldfd == -1)
{
perror("socket");
return -1;
}
int k = 1;
if(setsockopt(oldfd,SOL_SOCKET,SO_REUSEADDR,&k,sizeof(k))==-1)
{
perror("setsockopt");
return -1;
}
//2.bind
struct sockaddr_in sin={
.sin_family =AF_INET,
.sin_port = htons(SERPORT),
.sin_addr.s_addr = inet_addr(SERIP),
};
if(bind(oldfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("bind");
return -1;
}
//3.listen
if(listen(oldfd,CLIENTSIZE)==-1)
{
perror("listen");
return -1;
}
printf("listen success\n");
struct sockaddr_in cin[CLIENTSIZE];
char buff[1024];
int newfd;
int client_count = 0;
struct pollfd fds[CLIENTSIZE+1];
fds[0].fd = oldfd;
fds[0].events = POLLIN;
while(1){
int poll_count = poll(fds,client_count+1,-1);
if(poll_count==-1)
{
perror("poll");
return -1;
}
if(poll_count == 0)
{
printf("timeout");
return -1;
}
if(fds[0].revents == POLLIN)
{
struct sockaddr_in client;
int clnlen = sizeof(client);
newfd= accept(oldfd,(struct sockaddr*)&client,&clnlen);
if(newfd== -1)
{
perror("accept");
return -1;
}
if(client_count < CLIENTSIZE)
{
cin[client_count] = client;
fds[client_count+1].fd = newfd;
fds[client_count+1].events = POLLIN;
printf("%s:%d进入聊天室\n",inet_ntoa(cin[client_count].sin_addr),ntohs(cin[client_count].sin_port));
client_count++;
}
else{
printf("聊天室满了,已达%d\n人",client_count+1);
close(newfd);
}
}
for(int i =1;i<=client_count;i++)
{
if(fds[i].revents == POLLIN)
{
memset(buff,0,sizeof(buff));
int len = recv(fds[i].fd,buff,sizeof(buff),0);//阻塞接受
if(len == 0)
{
printf("%s:%d退出聊天室",inet_ntoa(cin[i-1].sin_addr),ntohs(cin[i-1].sin_port));
close(fds[i].fd);
for(int j = i;j<client_count;j++)
{
cin[j-1]=cin[j];
fds[j]=fds[j+1];
}
client_count--;
i--;
}
else{
buff[strlen(buff)-1]='\0';
printf("收到%s:%d的消息%s\n",inet_ntoa(cin[i-1].sin_addr),ntohs(cin[i-1].sin_port),buff);
for(int j =1;j<=client_count;j++)
{
if(j!=i)//不发给自己
{
send(fds[j].fd,buff,sizeof(buff),0);
}
}
}
}
}
}
for (int i = 0; i <= client_count; i++) {
close(fds[i].fd);
}
return 0;
}