多进程客户端-服务器模型
生活随笔
收集整理的這篇文章主要介紹了
多进程客户端-服务器模型
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
多進程服務器 -- 實現字符回射
服務器端
/************************************************************************* * File Name: echoserverp.c * Author: Chen WenKe * Email: chenwenke666@gmail.com * Blog: https://caotanxiaoke.github.io * Created Time: Sun 18 Jun 2017 05:47:46 PM PDT * * Description: 多進程并發 客戶端-服務器, 完成回射功能。 ************************************************************************/#include "csapp.h"void echo(int fd); void sigchld_handler(int sig) {while (waitpid(-1, 0, WNOHANG) > 0);return; }int main(int argc, char **argv) {int listenfd, connfd, port; socklen_t clientlen = sizeof(struct sockaddr_in);struct sockaddr_in clientaddr;if (argc != 2){fprintf(stderr, "usage: %s <port>\n", argv[0]);exit(0);}port = atoi(argv[1]); Signal(SIGCHLD, sigchld_handler);listenfd = Open_listenfd(port);while(1){connfd = Accept(listenfd, (SA *) &clientaddr, &clientlen);if(Fork() == 0){Close(listenfd); echo(connfd); Close(connfd);exit(0);}Close(connfd); } }void echo(int connfd) {int n; char buf[MAXLINE]; rio_t rio; Rio_readinitb(&rio, connfd); while(( n= Rio_readlineb(&rio, buf, MAXLINE)) != 0){printf("server received %d bytes\n", n); Rio_writen(connfd, buf, n); } }客戶端
/************************************************************************* * File Name: echoclient.c * Author: Chen WenKe * Email: chenwenke666@gmail.com * Blog: https://caotanxiaoke.github.io * Created Time: Sun 18 Jun 2017 08:00:49 PM PDT * * Description: ************************************************************************/#include "csapp.h"int main(int argc, char **argv) {int clientfd, port; char *host, buf[MAXLINE];rio_t rio;if (argc != 3){fprintf(stderr, "usage: %s <host> <port>\n", argv[0]);exit(0); }host = argv[1]; port = atoi(argv[2]);clientfd = Open_clientfd(host, port); Rio_readinitb(&rio, clientfd); while (Fgets(buf, MAXLINE, stdin) != NULL){Rio_writen(clientfd, buf, strlen(buf)); Fputs(buf, stdout); }Close(clientfd);exit(0); }
上面代碼中所使用的頭文件及編譯方法
轉載于:https://www.cnblogs.com/acm1314/p/7050301.html
總結
以上是生活随笔為你收集整理的多进程客户端-服务器模型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android ScrollView 控
- 下一篇: 谈谈跨界在软件开发中存在的意义