标签:
经过小小改动,把前面基础的例子做出一点修改。
并发服务器,服务器每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] = 0; fputs(recv, stdout); } } int main(int argc, char *argv[]) { int sockfd, n; char recvline[MAXLINE+1]; struct sockaddr_in servaddr; if (argc != 2) { fprintf(stderr, "usage: client_tcp <IP>\n"); exit(1); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { fprintf(stderr, "socket error\n"); exit(1); } bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) { fprintf(stderr, "inet_pton error for %s\n", argv[1]); exit(1); } if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { fprintf(stderr, "connect error\n"); exit(1); } process(stdin, sockfd); exit(0); }
/*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; char buff[MAXLINE+1]; while ((n = read(sockfd, buff, MAXLINE)) > 0) { 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, 0); 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); while (1) { int clilen = sizeof(cliaddr); connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen); if ((pid = fork()) == 0) {//child close(listenfd); process(connfd); exit(0); } close(connfd); } exit(0); }
标签:
原文地址:http://www.cnblogs.com/huanglianjing/p/4323103.html