经过小小改动,把前面基础的例子做出一点修改。
并发服务器,服务器每accept一个请求就fork()一个新的子进程。
编译运行方法同前一篇。
/*client_tcp.c*/ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #define MAXLINE 4096 #define PORT 12345 void process(FILE *fp, int sockfd) { char send[MAXLINE], recv[MAXLINE]; while (fgets(send, MAXLINE, fp) != NULL) { write(sockfd, send, strlen(send)); int n = read(sockfd, recv, MAXLINE); recv[n] = ; fputs(recv, stdout); } } int main(int argc, char *argv[]) { int sockfd, n; ]; struct sockaddr_in servaddr; ) { fprintf(stderr, "usage: client_tcp <IP>\n"); exit(); } )) < ) { fprintf(stderr, "socket error\n"); exit(); } bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); ], &servaddr.sin_addr) <= ) { fprintf(stderr, ]); exit(); } if (connect(sockfd, (struct sockaddr *) &servaddr, ) { fprintf(stderr, "connect error\n"); exit(); } process(stdin, sockfd); exit(); }
/*server_tcp.c*/ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #define MAXLINE 4096 #define LISTENQ 1024 #define PORT 12345 void process(int sockfd) { ssize_t n; ]; ) { write(sockfd, buff, n); } } int main(int argc, char *argv[]) { int listenfd, connfd; struct sockaddr_in servaddr, cliaddr; pid_t pid; listenfd = socket(AF_INET, SOCK_STREAM, ); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(PORT); bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); listen(listenfd, LISTENQ); ) { int clilen = sizeof(cliaddr); connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen); ) {//child close(listenfd); process(connfd); exit(); } close(connfd); } exit(); }