-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat-server.c
More file actions
48 lines (40 loc) · 1.04 KB
/
chat-server.c
File metadata and controls
48 lines (40 loc) · 1.04 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
#include <unistd.h>
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <poll.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address = {
.sin_family = AF_INET,
.sin_port = htons(9999),
.sin_addr.s_addr = INADDR_ANY
};
bind(sockfd, (struct sockaddr*)&address, sizeof(address));
listen(sockfd, 10);
int clientfd = accept(sockfd, NULL, NULL);
struct pollfd fds[2] = {
{
.fd = 0,
.events = POLLIN,
.revents = 0
},
{
.fd = clientfd,
.events = POLLIN,
.revents = 0
}
};
for (;;) {
char buffer[256] = {0};
poll(fds, 2, 50000);
if (fds[0].revents & POLLIN) {
read(0, buffer, 255);
send(clientfd, buffer, 255, 0); // no need of flags
} else if (fds[1].revents & POLLIN) {
recv(clientfd, buffer, 255, 0);
printf("%s\n", buffer);
}
}
return 0;
}