回射程序:服务端将客户端发送的数据输出并返回给客户端
客户端
1 #include "net.h"
2
3 int main(int argc, char **argv)
4 {
5 int sockfd, n;
6 char sendline[MAXLINE], recvline[MAXLINE + 1];
7 struct sockaddr_in servaddr;
8
9 if (argc != 2)
10 {
11 printf("Error arg!\n");
12 exit(1);
13 }
14
15 if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
16 {
17 printf("Error socket!\n");
18 exit(1);
19 }
20
21 bzero(&servaddr, sizeof(servaddr));
22 servaddr.sin_family = AF_INET;
23 servaddr.sin_port = htons(SERV_PORT);
24
25 if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
26 {
27 printf("Error inet_pton!\n");
28 exit(1);
29 }
30
31 if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
32 {
33 printf("Error connect!\n");
34 exit(1);
35 }
36
37 printf("Success init!\n");
38
39 while (fgets(sendline, MAXLINE, stdin) != NULL)
40 {
41 printf("Success fget from stdin!\n");
42
43 if (write(sockfd, sendline, strlen(sendline)) < 0)
44 {
45 printf("Error write!\n");
46 exit(1);
47 }
48
49 if ( (n = read(sockfd, recvline, MAXLINE)) > 0 )
50 {
51 recvline[n] = '\0';
52 fputs(recvline, stdout);
53 }
54 }
55
56 return 0;
57
服务端
服务端:
1 #include "net.h"
2
3 int main(int argc, char **argv)
4 {
5 int listenfd, connfd, n;
6 struct sockaddr_in servaddr, cliaddr;
7 char buff[MAXLINE];
8 pid_t childpid;
9 socklen_t clilen;
10
11 if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
12 {
13 printf("Error socket!\n");
14 exit(0);
15 }
16
17 bzero(&servaddr, sizeof(servaddr));
18 servaddr.sin_family = AF_INET;
19 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
20 servaddr.sin_port = htons(SERV_PORT);
21
22 if (bind(listenfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
23 {
24 printf("Error bind!\n");
25 exit(1);
26 }
27
28 if (listen(listenfd, LISTENQ) < 0)
29 {
30 printf("Error listen!\n");
31 exit(1);
32 }
33
34 printf("Success init!\n");
35
36 for ( ; ; )
37 {
38 clilen = sizeof(cliaddr);
39
40 if ( (connfd = accept(listenfd, (SA *) &cliaddr, &clilen)) < 0 )
41 {
42 printf("Error accept!\n");
43 exit(0);
44 }
45
46 if ( (childpid = fork()) == 0 )
47 {
48 if (close(listenfd) < 0)
49 {
50 printf("Error close!\n");
51 exit(1);
52 }
53
54 while ( (n = read(connfd, buff, MAXLINE)) > 0 )
55 {
56 buff[n] = '\0';
57 fputs(buff, stdout);
58
59 if (write(connfd, buff, strlen(buff)) < 0)
60 {
61 printf("Error write!\n");
62 exit(1);
63 }
64 }
65
66 exit(0);
67 }
68 }
69
运行结果:
[wangml@iZwz976helaylvgqok97prZ net]$ ./chat_cli 120.24.55.49
Success init!
qwer
Success fget from stdin!
qwer
sds
Success fget from stdin!
sds
Success fget from stdin!
^C
[root@iZwz976helaylvgqok97prZ net]# ./chat_ser
Success init!
qwer
sds
^C
转载请注明出处