-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.c
98 lines (79 loc) · 2.06 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
96
97
98
#include "client.h"
char buffer[BUFFER_SIZE] = {0};
size_t l_buffer;
int hold_flag = 0;
void *receiver(void *arg)
{
int sock = (int)(intptr_t)arg;
char rbuffer[BUFFER_SIZE] = {0};
while (1)
{
memset(rbuffer, 0, BUFFER_SIZE);
int err = receive_message(sock, rbuffer, BUFFER_SIZE);
if (err < 0)
{
printf("\ndisconnected from server\n");
exit(err);
}
checkNResize();
add_message(rbuffer, strlen(rbuffer));
hold_flag = 1;
render_ui(buffer);
hold_flag = 0;
}
}
int main(int argc, char const *argv[])
{
// check argument
if (argc < 3)
{
printf("Usage: %s <address> <port>\n", argv[0]);
return -1;
}
const char *address = argv[1];
int port = atoi(argv[2]);
int sock = 0, client_fd;
struct sockaddr_in serv_addr;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
if (inet_pton(AF_INET, address, &serv_addr.sin_addr) <= 0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if ((client_fd = connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr))) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
printf("Enter your name: ");
fgets(buffer, BUFFER_SIZE, stdin);
int err = send_message(sock, buffer, strlen(buffer) - 1);
if (err)
{
perror("write() failed");
exit(err);
}
memset(buffer, 0, BUFFER_SIZE);
message_init();
pthread_t tid;
pthread_create(&tid, NULL, receiver, (void *)(intptr_t)sock);
while (1)
{
memset(buffer, 0, BUFFER_SIZE);
l_buffer = get_input_noncanon(buffer, BUFFER_SIZE, &hold_flag);
int err = send_message(sock, buffer, l_buffer);
if (err)
{
perror("write() failed");
exit(err);
}
}
close(client_fd);
return 0;
}