-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat-client.c
More file actions
55 lines (43 loc) · 1.24 KB
/
Copy pathchat-client.c
File metadata and controls
55 lines (43 loc) · 1.24 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
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <poll.h>
int main(void) {
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in address = {
AF_INET,
htons(9999),
0
};
connect(server_socket, (struct sockaddr *) &address, sizeof(address));
int client_socket = accept(server_socket, NULL, NULL);
//getting input from user
struct pollfd fds[2] = { // two structures so we listen to any messages coming from the client
{
0,
POLLIN, //if there's data to be read
0
},
{
server_socket,
POLLIN,
0
}
};
for (;;) {
char buffer[256] = { 0 };
poll(fds, 2, 50000); // in miliseconds
if (fds[0].revents & POLLIN) {
read(0, buffer, 255);
send(server_socket, buffer, 255, 0);
} else if (fds[1].revents & POLLIN) { // if this is true, it means there's something to be read from the client
if (recv(server_socket, buffer, 255, 0) == 0) {
return 0;
}
printf("%s\n", buffer);
}
}
return 0;
}