-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
124 lines (112 loc) · 2.39 KB
/
server.cpp
File metadata and controls
124 lines (112 loc) · 2.39 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "config.h"
int main()
{
int sockFd,clientFd,client[FD_SETSIZE];
fd_set allset, rset;
int nready, maxfd, maxi=-1;
socklen_t clilen;
sockaddr_in serveraddr, clientaddr;
printf("Start Server.\n");
if((sockFd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket error.");
exit(1);
}
printf("Create socket.\n");
bzero(&serveraddr, sizeof(serveraddr));
bzero(&clientaddr, sizeof(clientaddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(PORT);
if(bind(sockFd, (sockaddr *)&serveraddr, sizeof(sockaddr)) < 0)
{
perror("bind error.");
exit(1);
}
printf("Bind Port:%d\n", PORT);
if(listen(sockFd, LISTENQ) < 0)
{
perror("listen error.");
exit(1);
}
printf("Listen.\n");
FD_ZERO(&allset);
FD_SET(sockFd, &allset);
maxfd = sockFd;
for(int i=0;i<FD_SETSIZE;i++)
{
client[i] = -1;
}
while(1)
{
rset = allset;
if((nready = select(maxfd+1, &rset, NULL, NULL, NULL)) < 0)
{
perror("select error");
exit(1);
}
if(FD_ISSET(sockFd, &rset))
{
clilen = sizeof(sockaddr);
int i;
if((clientFd = accept(sockFd, (sockaddr *)&clientaddr, &clilen)) < 0)
{
perror("accept error.");
exit(1);
}
printf("New client[%s:%d] connected.\n", inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port);
for(i=0;i<FD_SETSIZE; i++)
{
if(client[i] < 0)
{
client[i] = clientFd;
break;
}
}
if(i == FD_SETSIZE)
{
perror("Too many connection.");
exit(1);
}
FD_SET(clientFd, &allset);
maxfd = maxfd > clientFd ? maxfd : clientFd;
maxi = maxi > i ? maxi : i;
if(--nready <= 0)
continue;
}
for(int i=0;i<=maxi;++i)
{
if(client[i] < 0)
continue;
if(FD_ISSET(client[i], &rset))
{
if(getpeername(client[i], (sockaddr *)&clientaddr, &clilen) < 0)
{
perror("getpeername error.");
exit(1);
}
printf("Receive from[%s:%d]:\n", inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port);
int buffLen;
char buff[MAX_LINE];
if((buffLen = read(client[i], buff, MAX_LINE)) <= 0)
{
close(client[i]);
client[i] = -1;
FD_CLR(client[i], &allset);
}
else
{
printf("\t%s", buff);
printf("Send msg back.\n");
if(write(client[i], buff, buffLen) < 0)
{
perror("write error.");
}
}
if(--nready <= 0)
continue;
}
}
}
return 0;
}