TCP/IP网络编程 学习笔记_11 --多进程服务器端( 二 )


////main.cpp//hello_client////Created by app05 on 15-8-18.//Copyright (c) 2015年 app05. All rights reserved.////客服端I/O分割,父进程负责接收数据,子进程负责发送数据,分开处理#include #include #include #include #include #include #define BUF_SIZE 1024void error_handling(char *message);void read_routime(int sock, char *buf);//接收数据void write_routine(int sock, char *buf);//发送数据int main(int argc, const char * argv[]) {int sock;pid_t pid;char buf[BUF_SIZE];struct sockaddr_in serv_adr;if(argc != 3){printf("Usage: %s \n", argv[0]);exit(1);}sock = socket(PF_INET, SOCK_STREAM, 0);if(sock == -1)error_handling("socket() error");memset(&serv_adr, 0, sizeof(serv_adr));serv_adr.sin_family = AF_INET;serv_adr.sin_addr.s_addr = inet_addr(argv[1]);serv_adr.sin_port = htons(atoi(argv[2]));if (connect(sock, (struct sockaddr *) &serv_adr, sizeof(serv_adr)) == -1)error_handling("connect() error");/*客服端I/O分割,父进程负责接收数据,子进程负责发送数据 。这样分开可以提高频繁交换数据的程序性能,而不用像以前一样,只有完全接收上一条数据后才能发送下一条 。*/pid = fork();if(pid == 0)write_routine(sock, buf);elseread_routime(sock, buf);close(sock);return 0;}void error_handling(char *message){fputs(message, stderr);fputc('\n', stderr);exit(1);}void read_routime(int sock, char *buf){while (1) {int str_len = read(sock, buf, BUF_SIZE);if(str_len == 0)return;buf[str_len] = 0;printf("Message from server: %s", buf);}}void write_routine(int sock, char *buf){while (1){fgets(buf, BUF_SIZE, stdin);if (!strcmp(buf, "q\n") || !strcmp(buf, "Q\n")){shutdown(sock, SHUT_WR);}write(sock, buf, strlen(buf));}}

TCP/IP网络编程 学习笔记_11 --多进程服务器端

文章插图

TCP/IP网络编程 学习笔记_11 --多进程服务器端

文章插图