-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.c
More file actions
61 lines (51 loc) · 1.45 KB
/
client.c
File metadata and controls
61 lines (51 loc) · 1.45 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
/*
* Client for Bank Management System
* Author: Piyush Singh
*/
#include "common.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {0};
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
printf("Connection failed\n");
return 1;
}
printf("Connected to server\n\n");
setvbuf(stdout, NULL, _IONBF, 0);
char buffer[BUFFER_SIZE];
char input[BUFFER_SIZE];
struct pollfd fds[2];
fds[0].fd = sock;
fds[0].events = POLLIN;
fds[1].fd = STDIN_FILENO;
fds[1].events = POLLIN;
while (1) {
if (poll(fds, 2, 100) > 0) {
if (fds[0].revents & POLLIN) {
memset(buffer, 0, BUFFER_SIZE);
int n = read(sock, buffer, BUFFER_SIZE - 1);
if (n <= 0) break;
printf("%s", buffer);
}
if (fds[1].revents & POLLIN) {
if (!fgets(input, BUFFER_SIZE, stdin)) break;
input[strcspn(input, "\n")] = 0;
if (write(sock, input, strlen(input)) <= 0) break;
}
}
}
close(sock);
printf("\nDisconnected\n");
return 0;
}