1. 程式人生 > >Linux----網路程式設計(TCP網路通訊客戶端伺服器程式設計實現多程序)

Linux----網路程式設計(TCP網路通訊客戶端伺服器程式設計實現多程序)

1、伺服器ser.c

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <unistd.h>
  4 #include <assert.h>
  5 #include <string.h>
  6 #include <sys/socket.h>
  7 #include <netinet/in.h>
  8 #include <arpa/inet.h>
  9 #include <pthread.h>
 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 <string.h>
  2 #include <stdio.h>
  3 #include <stdlib.h>
  4 #include <unistd.h>
  5 #include <assert.h>
  6 #include <sys/socket.h>
  7 #include <netinet/in.h>
  8 #include <arpa/inet.h>
  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     }