-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
65 lines (60 loc) · 2.18 KB
/
server.cpp
File metadata and controls
65 lines (60 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "utility.h"
int main()
{
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(SERVER_PORT);
serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
//创建监听socket
int listenfd = socket(PF_INET, SOCK_STREAM, 0);
if(listenfd < 0) { perror("listenfd"); exit(-1);}
if(bind(listenfd, (sockaddr*)&serverAddr, sizeof(sockaddr)) < 0)
{
perror("bind error");
exit(-1);
}
int ret = listen(listenfd, 5);
if(ret < 0) { perror("listen error"); exit(-1); }
int epfd = epoll_create(EPOLL_SIZE);
if(epfd < 0) { perror("epfd error"); exit(-1); }
static struct epoll_event events[EPOLL_SIZE];
addfd(epfd, listenfd, true);
while(1)
{
int epoll_events_count = epoll_wait(epfd, events, EPOLL_SIZE, -1);
if(epoll_events_count < 0)
{
perror("epoll failure");
break;
}
for(int i = 0; i < epoll_events_count; i ++)
{
int sockfd = events[i].data.fd;
if(sockfd == listenfd)
{
struct sockaddr_in clientAddr;
socklen_t client_addrLen = sizeof(struct sockaddr_in);
int clientfd = accept(sockfd, (sockaddr*)&clientAddr, &client_addrLen);
printf("client connection from: %s : %d(IP : port), clientfd = %d \n",
inet_ntoa(clientAddr.sin_addr),
ntohs(clientAddr.sin_port),
clientfd);
addfd(epfd, clientfd, true);
clients_list.push_back(clientfd);
printf("Now there are %d clients in the chat room\n", (int)clients_list.size());
char message[BUF_SIZE];
memset(message,'\0', BUF_SIZE);
sprintf(message, SERVER_WELCOME, clientfd);
int ret = send(clientfd, message, BUF_SIZE, 0);
if(ret < 0) { perror("send error"); exit(-1); }
}
else if(events[i].events & EPOLLIN)
{
int ret = sendBroadcastmessage(sockfd);
}
else break;
}
}
close(listenfd);
close(epfd);
}