Linux----网络编程(TCP网络通信客户端服务器编程实现多进程)

1、服务器ser.c

  1 #include 
  2 #include 
  3 #include 
  4 #include 
  5 #include 
  6 #include 
  7 #include 
  8 #include 
  9 #include 
 10 
 11 //客户端服务器实现多进程
 12 void* fun(void * arg)
 13 {
 14     int c = (int)arg;
 15     while(1)
 16     {
 17         char buff[128] = {0};
 18         int n = recv(c, buff, 127, 0);
 19         if(n <= 0)
 20         {
 21             break;
 22             }
 23         printf("buff(%d)=%s\n",c,buff);
 24         send(c, "ok", 2, 0);
 25         }
 26     printf("one client over\n");
 27     close(c);
 28     }
 29 
 30 int main()
 31 {
 32     int sockfd = socket(AF_INET, SOCK_STREAM, 0);
 33     assert(sockfd != -1);
 34 
 35     struct sockaddr_in saddr, caddr;
 36     memset(&saddr, 0, sizeof(saddr));
 37     saddr.sin_family = AF_INET;
 38     saddr.sin_port = htons(6000);
 39     saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
 40 
 41     int res = bind(sockfd,(struct sockaddr*)&saddr, sizeof(saddr));
 42     assert(res != -1);
 43 
 44     listen(sockfd, 5);
 45 
 46     while(1)
 47     {
 48         int len = sizeof(caddr);
 49         int c = accept(sockfd,(struct sockaddr*)&caddr, &len);
 50         if(c < 0)
 51         {
 52             continue;
 53             }
 54         printf("accept c=%d, ip=%s\n",inet_ntoa(caddr.sin_addr));
 55 
 56         pid_t pid = fork();
 57         if(pid < 0)
 58         {
 59             close(c);
 60             continue;
 61             }
 62         if(pid == 0)
 63         {
 64             //send() recv()
 65             close(c);
 66             exit(0);
 67             }
 68         close(c);
 69         }
 70     }
                     

2、客户端cli.c(没有做改变)

  1 #include 
  2 #include 
  3 #include 
  4 #include 
  5 #include 
  6 #include 
  7 #include 
  8 #include 
  9 
 10 
 11 int main()
 12 {
 13     int sockfd = socket(AF_INET, SOCK_STREAM, 0);
 14     assert(sockfd != -1);
 15     struct sockaddr_in saddr;
 16     memset(&saddr, 0, sizeof(saddr));
 17     saddr.sin_family = AF_INET;
 18     saddr.sin_port = htons(6000);
 19     saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
 20 
 21     int res = connect(sockfd,(struct sockaddr*)&saddr, sizeof(saddr));
 22     assert(res != -1);
 23 
 24     while(1)
 25     {
 26         char buff[128] = {0};
 27         printf("input:\n");
 28         fgets(buff,128,stdin);
 29         if(strncmp(buff,"end",3) == 0)
 30         {
 31             break;
 32             }
 33         send(sockfd, buff, strlen(buff), 0);
 34         memset(buff, 0, 128);
 35         recv(sockfd, buff, 127, 0);//127改为1,表示一个一个接收
 36         printf("buff=%s\n",buff);
 37         }
 38       close(sockfd);
 39       exit(0);
 40     }

 

你可能感兴趣的:(Linux)