6.2. 簡單的 Stream Client
Client 這傢伙比 server 簡單多了,client 所需要做的就是:連線到你在命令列所指定的主機 3490 port,接著,client 會收到 server 送回的字串。
Client 的程式碼 [21]:
1
/*
2
/*
3
** client.c -- 一個 stream socket client 的 demo
4
*/
5
#include <stdio.h>
6
#include <stdlib.h>
7
#include <unistd.h>
8
#include <errno.h>
9
#include <string.h>
10
#include <netdb.h>
11
#include <sys/types.h>
12
#include <netinet/in.h>
13
#include <sys/socket.h>
14
#include <arpa/inet.h>
15
16
#define PORT "3490" // Client 所要連線的 port
17
#define MAXDATASIZE 100 // 我們一次可以收到的最大位原組數(number of bytes)
18
19
// 取得 IPv4 或 IPv6 的 sockaddr:
20
void *get_in_addr(struct sockaddr *sa)
21
{
22
if (sa->sa_family == AF_INET) {
23
return &(((struct sockaddr_in*)sa)->sin_addr);
24
}
25
26
return &(((struct sockaddr_in6*)sa)->sin6_addr);
27
}
28
29
int main(int argc, char *argv[])
30
{
31
int sockfd, numbytes;
32
char buf[MAXDATASIZE];
33
struct addrinfo hints, *servinfo, *p;
34
int rv;
35
char s[INET6_ADDRSTRLEN];
36
37
if (argc != 2) {
38
fprintf(stderr,"usage: client hostname\n");
39
exit(1);
40
}
41
42
memset(&hints, 0, sizeof hints);
43
hints.ai_family = AF_UNSPEC;
44
hints.ai_socktype = SOCK_STREAM;
45
46
if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) {
47
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
48
return 1;
49
}
50
51
// 用迴圈取得全部的結果,並先連線到能成功連線的
52
for(p = servinfo; p != NULL; p = p->ai_next) {
53
if ((sockfd = socket(p->ai_family, p->ai_socktype,
54
p->ai_protocol)) == -1) {
55
perror("client: socket");
56
continue;
57
}
58
59
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
60
close(sockfd);
61
perror("client: connect");
62
continue;
63
}
64
65
break;
66
}
67
68
if (p == NULL) {
69
fprintf(stderr, "client: failed to connect\n");
70
return 2;
71
}
72
73
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
74
75
printf("client: connecting to %s\n", s);
76
77
freeaddrinfo(servinfo); // 全部皆以這個 structure 完成
78
79
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
80
perror("recv");
81
exit(1);
82
}
83
84
buf[numbytes] = '\0';
85
printf("client: received '%s'\n",buf);
86
87
close(sockfd);
88
return 0;
89
}
要注意的是,你如果沒有在執行 client 以前先啟動 server 的話,connect() 會傳回 "Connection refused",這個訊息很有 幫助。
Last modified 9mo ago