This repository has been archived by the owner on Apr 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.c
95 lines (84 loc) · 1.87 KB
/
client.c
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
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <poll.h>
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage %s <port>\n", argv[0]);
return 1;
}
int port = atoi(argv[1]);
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd < 0)
{
perror("Socket connection failed");
return 1;
}
// Create the server addr struct
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
inet_aton("192.168.60.174", &server_addr.sin_addr);
int ret = connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (ret < 0)
{
perror("Connection failed");
return 1;
}
struct pollfd fds[2];
fds[0].fd = STDIN_FILENO;
fds[0].events = POLLIN;
fds[1].fd = sock_fd;
fds[1].events = POLLIN;
while (1)
{
int ret = poll(fds, 2, -1);
if (ret < 0)
{
perror("Poll failed");
return 1;
}
if (fds[0].revents & POLLIN)
{
char buffer[1024];
fgets(buffer, 1023, stdin);
// Check if the user input is "/quit"
if (strcmp(buffer, "/quit\n") == 0)
{
break;
}
int n = write(sock_fd, buffer, strlen(buffer));
if (n < 0)
{
perror("Error when sending the message");
return 1;
}
}
if (fds[1].revents & POLLIN)
{
char buffer[1024];
int n = read(sock_fd, buffer, sizeof(buffer) - 1);
if (n < 0)
{
perror("Error when reading the message");
return 1;
}
if (n == 0)
{
fprintf(stderr, "Connection terminated by the server\n");
break;
}
buffer[n] = '\0';
printf("%s", buffer);
}
}
// Close the socket
shutdown(sock_fd, SHUT_RDWR);
close(sock_fd);
return 0;
}