/
client.c
89 lines (61 loc) · 1.75 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
#include <stdio.h>
#include "csapp.h"
// TODO: need a way to interrupt the Fgets call if server closes connection
int active;
void * keyboard(void * vargp) {
char buf[MAXLINE];
rio_t rio;
fprintf(stderr,"fprintf 7\n");
int clientfd = *((int*) vargp);
fprintf(stderr,"fprintf 8\n");
Rio_readinitb(&rio, clientfd);
while(Fgets(buf, MAXLINE, stdin) != NULL) {
fprintf(stderr,"fprintf 9\n");
if(active)
Rio_writen(clientfd, buf, strlen(buf));
else
break;
}
if(active) {
fprintf(stderr,"fprintf 10\n");
strcpy(buf, "$q\n");
Rio_writen(clientfd, buf, strlen(buf));
}
return NULL;
}
int main(int argc, char * argv[]) {
int clientfd;
char *host, buf[MAXLINE];
int port;
rio_t rio;
pthread_t tid;
fprintf(stderr,"fprintf 1\n");
if(argc < 3) {
fprintf(stderr, "usage: %s <host> <port>\n", argv[0]);
exit(0);
}
host = argv[1];
port = atoi(argv[2]);
fprintf(stderr,"fprintf 2\n");
clientfd = Open_clientfd(host, port);
fprintf(stderr,"fprintf 3\n");
active = 1;
Pthread_create(&tid, NULL, keyboard, &clientfd);
fprintf(stderr,"fprintf 4\n");
Rio_readinitb(&rio, clientfd);
while(Rio_readlineb(&rio, buf, MAXLINE) != 0) {
fprintf(stderr,"fprintf 5\n");
if(strcmp(buf, "$q") == 0) {
printf("received $q command from server\n");
active = 0;
}
else {
fprintf(stderr,"fprintf 6\n");
Fputs(buf, stdout);
}
}
Close(clientfd);
/* note: if the server closes the connection, the keyboard thread
will be in Fgets and will try to write to a closed connection... */
return 0;
}