-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
98 lines (87 loc) · 2.03 KB
/
server.c
File metadata and controls
98 lines (87 loc) · 2.03 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
#include<sys/socket.h>
#include<fcntl.h>
#include<stdio.h>
#include<arpa/inet.h>
#include<poll.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>
#define MAXCLIENTS 10
int main(){
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address = {
AF_INET,
htons(8888),
0
};
if (bind(sockfd, &address, sizeof(address)) != 0){
perror("failed to bind port");
printf("is a server already running on this port\n");
exit(1);
}
fcntl(sockfd, F_SETFL, O_NONBLOCK);
printf("%d\n",errno);
perror(0);
listen(sockfd, 10);
int clients[MAXCLIENTS];
int connectedClients[MAXCLIENTS] = { 0 };
int clientCount = 0;
struct pollfd fds[MAXCLIENTS];
while (0 == 0){
usleep(50000);
for (int i = 0; i < clientCount+1; i++){
if (connectedClients[i] == 0){
int tmp = accept(sockfd, 0, 0);
if (tmp != -1){
clients[i] = tmp;
printf("client connected\n");
fds[i].fd = clients[i];
fds[i].events = POLLIN;
fds[i].revents = 0;
connectedClients[i] = 1;
clientCount++;
FILE *fptr;
fptr = fopen("./log", "a+");
fprintf(fptr, "\n");
char tosend[255];
while (fgets(tosend, 255, fptr) != NULL){
send(clients[i], strtok(tosend, "\n"), 255, 0);
}
fclose(fptr);
}
}
}
poll(fds, MAXCLIENTS, 50000);
char buffer[256];
int tmp = clientCount;
for (int i = 0; i < tmp; i++){
if (connectedClients[i] == 1){
if (fds[i].revents & POLLIN){
if (recv(clients[i], buffer, 255, 0) == 0){ break; }
else if (strcmp(buffer, "/exit") == 0){
connectedClients[i] = 0;
clientCount--;
fds[i].revents = 0;
fds[i].fd = 0;
fds[i].events = 0;
close(clients[i]);
printf("client %d disconnected\n", i);
} else {
FILE *log;
log = fopen("./log", "a");
fprintf(log, "%s\n", buffer);
fclose(log);
for (int j = 0; j < clientCount; j++){
if (j != i){
send(clients[j], buffer, 255, 0);
}
}
}
}
}
}
}
close(sockfd);
return 0;
}