blob: 0b9cbfe998bf12bcf651946a58cbd71cae3476a8 (
plain)
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
|
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdio.h>
#include "util.h"
int
main()
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
panic("socket creation error");
struct sockaddr_in serv_addr;
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
serv_addr.sin_port = htons(8888);
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
panic("socket connect error");
for (;;) {
char buf[1024];
bzero(&buf, sizeof(buf));
scanf("%s", buf);
ssize_t n_write_bytes = write(sockfd, buf, sizeof(buf));
if (n_write_bytes == -1) {
printf("socket already disconnected, cannot write any more!\n");
break;
}
ssize_t n_read_bytes = read(sockfd, buf, sizeof(buf));
if (n_read_bytes > 0) {
printf("message from server: %s\n", buf);
} else if (n_read_bytes == 0) {
printf("server socket disconnected!\n");
break;
} else if (n_read_bytes == -1) {
close(sockfd);
panic("socket read error");
}
}
}
|