回射程序改良,将源main函数中的某些操作定义为单独的函数,使其便于修改
chat_cli.c 文件
1 #include "net.h" 2 3 int main(int argc, char **argv) 4 { 5 int sockfd; 6 7 if (argc != 2) 8 { 9 printf("Error arg! "); 10 exit(1); 11 } 12 sockfd = tcp_connect(argv[1], SERV_PORT); 13 printf("Success init! "); 14 cli_io(sockfd); 15 16 return 0; 17 }
fun_cli.c 文件
1 #include "net.h" 2 3 // 建立一个TCP套接字(IPv4),并与给定主机端口连接,并返回连接后的套接字 4 int tcp_connect(char *ser_ip, int port) 5 { 6 int sockfd; 7 struct sockaddr_in servaddr; 8 9 if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) 10 { 11 printf("Error socket! "); 12 exit(1); 13 } 14 15 bzero(&servaddr, sizeof(servaddr)); 16 servaddr.sin_family = AF_INET; 17 servaddr.sin_port = htons(port); 18 19 if (inet_pton(AF_INET, ser_ip, &servaddr.sin_addr) <= 0) 20 { 21 printf("Error inet_pton! "); 22 exit(1); 23 } 24 25 if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0) 26 { 27 printf("Error connect! "); 28 exit(1); 29 } 30 31 return sockfd; 32 } 33 34 // 回射程序客户端对套接字的读写 35 void cli_io(int sockfd) 36 { 37 int n; 38 char sendline[MAXLINE], recvline[MAXLINE]; 39 40 while (fgets(sendline, MAXLINE, stdin) != NULL) 41 { 42 if (write(sockfd, sendline, strlen(sendline)) < 0) 43 { 44 printf("Error write! "); 45 exit(1); 46 } 47 48 if ( (n = read(sockfd, recvline, MAXLINE)) > 0 ) 49 { 50 recvline[n] = '