Chinaunix首页 | 论坛 | 博客
  • 博客访问: 175772
  • 博文数量: 27
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 618
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-15 09:12
文章分类
文章存档

2014年(17)

2013年(10)

我的朋友

分类: C/C++

2014-03-12 17:45:24

写个电梯的socket的代码,这个是server代码,以后写程序可以更加熟练的使用这个代码了
server:

点击(此处)折叠或打开

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <signal.h>
  6. #include <fcntl.h>
  7. #include <pthread.h>
  8. #include <errno.h>

  9. #include <sys/wait.h>
  10. #include <sys/types.h>
  11. #include <sys/socket.h>
  12. #include <sys/stat.h>
  13. #include <sys/file.h>

  14. #include <arpa/inet.h>
  15. #include <netinet/in.h>

  16. static const char *service_pid_file = "/tmp/elevator_service.pid";
  17. enum elevator_status {
  18.         idle = 1, up, down
  19. };

  20. typedef struct {
  21.         int name; //Name
  22.         enum elevator_status status; //Status
  23.         int position; //Number of floor
  24.         struct tm * open_time; //Bootup time
  25.         struct tm * close_time; //Close time
  26.         struct tm * run_time; //Running time
  27.         struct tm * idle_time; //Idle time
  28. } elevator_class;

  29. int read_pid_file(const char *pid_file)
  30. {
  31.         FILE *f;
  32.         int pid = 0;

  33.         if ((f = fopen(pid_file, "r")) != NULL) {
  34.                 fscanf(f, "%d", &pid);
  35.                 fclose(f);
  36.         }
  37.         return (pid);

  38. }
  39. int check_elevator_service_process(void)
  40. {
  41.         int is_locked = 1;
  42.         int stored_pid = read_pid_file(service_pid_file);
  43.         
  44.         if ((stored_pid == 0) || (stored_pid == getpid()))
  45.                 is_locked = 0;
  46.         else
  47.                 if (kill(stored_pid, 0))
  48.                         is_locked = 0;
  49.         
  50.         return (is_locked);
  51. }

  52. int record_elevator_service_process(void)
  53. {
  54.         int success = 0;
  55.         FILE *fp = NULL;
  56.         int fd = -1;
  57.         int pid = 0;

  58.         if ((fd = open(service_pid_file, (O_RDWR | O_CREAT), 0644)) != -1) {
  59.                 if ((fp = fdopen(fd, "r+")) != NULL) {
  60.                         if (flock(fd, (LOCK_EX | LOCK_NB)) < 0) {
  61.                                 fscanf(fp, "%d", &pid);
  62.                                 printf("Can't lock process, lock held by pid %d", pid);
  63.                         }
  64.                         else {
  65.                                 pid = getpid();
  66.                                 if ((fprintf(fp, "%d", pid)) && (!fflush(fp)) && (!flock(fd, LOCK_UN))) {
  67.                                         success = 1;
  68.                                 }
  69.                         }
  70.                         fclose(fp);
  71.                 }
  72.                 close(fd);
  73.         }
  74.         return (success);
  75. }

  76. int server_socket(int num)
  77. {
  78.         int sfp;
  79.         struct sockaddr_in s_add;
  80.         unsigned short port = 0x8888;

  81.         sfp = socket(AF_INET, SOCK_STREAM, 0);
  82.         if(sfp == -1)
  83.         {
  84.                 printf("Elevator service socket fail ! \r\n");
  85.                 return -1;
  86.         }
  87.         printf("Elevator service socket ok !\r\n");


  88.         bzero(&s_add,sizeof(struct sockaddr_in));
  89.         s_add.sin_family=AF_INET;
  90.         s_add.sin_addr.s_addr=htonl(INADDR_ANY);
  91.         s_add.sin_port=htons(port);

  92.         if(bind(sfp, (struct sockaddr *)(&s_add), sizeof(struct sockaddr)) == -1)
  93.         {
  94.                 printf("Elevator service bind fail !\r\n");
  95.                 return -1;
  96.         }
  97.         printf("Elevator service bind ok !\r\n");

  98.         if(listen(sfp, num) == -1)
  99.         {
  100.                 printf("Elevator service listen fail !\r\n");
  101.                 return -1;
  102.         }
  103.         printf("Elevator service listen ok\r\n");
  104.         
  105.         return sfp;
  106. }

  107. int elevator_accept_socket(int sockfd)
  108. {
  109.         struct sockaddr_in peer_addr;
  110.         char buff[20];
  111.         int sin_size = sizeof(peer_addr);
  112.         
  113.         memset(buff, 0, 20);
  114.         
  115.         int client_fd = accept(sockfd, (struct sockaddr *) &peer_addr, (socklen_t * __restrict__) &sin_size);
  116.         
  117.         printf("elevator client address is %d , sin_port is %d \n",
  118.                         ntohl(peer_addr.sin_addr.s_addr), ntohs(peer_addr.sin_port));
  119.         inet_ntop(AF_INET, (void *) &peer_addr.sin_addr, buff, 20);
  120.       
  121.         
  122.         return client_fd;
  123. }

  124. int recv_socket(int sockfd, void *buffer, int size)
  125. {
  126.         int result = -1;
  127.         
  128.         result = recv(sockfd, buffer, size, MSG_WAITALL);
  129.         
  130.         if (result == -1) {
  131.                 printf("there is no data to receive \n");
  132.         }
  133.         
  134.         return result;
  135. }

  136. int send_socket(int sockfd, void *buffer, int size)
  137. {
  138.         int result = -1;
  139.         
  140.         result = send(sockfd, buffer, size, MSG_DONTWAIT);
  141.         
  142.         if (result == -1) {
  143.                 printf("there is no data to receive \n");
  144.         }
  145.         
  146.         return result;
  147. }

  148. void Dispatchercmd(int client_fd)
  149. {
  150.         int num;
  151.         int lenth = 0;
  152.         elevator_class elevator;
  153.         int elevator_lenth = 0;

  154.         printf("DispatcherCmd \n");
  155.         printf("-------Evevator dispatcher commands begin\n");
  156.         
  157.         lenth = recv_socket(client_fd, &num, sizeof(num));
  158.         
  159.         if (lenth == -1) {
  160.                 printf("The receive floor_num error\n");
  161.                 goto err;
  162.         } else if (lenth == 0) {
  163.                 printf("The receive floor_num is Null\n");
  164.                 goto err;
  165.         } else {
  166.                 printf("recv num = %d\n", num);
  167.                 lenth = send_socket(client_fd, "OK", 3);
  168.                 if (lenth == -1) {
  169.                         printf("The send OK faile\n");
  170.                         goto err;
  171.                 }
  172.         }

  173.         elevator_lenth = recv_socket(client_fd, &elevator, sizeof(elevator));
  174.         
  175.         if (elevator_lenth == -1) {
  176.                 printf("The receive elevator data length error\n");
  177.                 goto err;
  178.         } else if (elevator_lenth == 0) {
  179.                 printf("The receive elevator data lenth is 0\n"); //notice
  180.                 goto err;
  181.         } else {
  182.                 printf("elevator.name = %d\n", elevator.name);
  183.                 printf("elevator.status = %d\n", elevator.status);
  184.         
  185.                 //TodoList:
  186.                 //Get user request and elevator status, return elevator function
  187.                 lenth = send_socket(client_fd, "Run", 4);
  188.                 if (lenth == -1) {
  189.                         printf("The send OK faile\n");
  190.                         goto err;
  191.                 }
  192.                 
  193.         }

  194. err:
  195.         close(client_fd);
  196. }
  197. int fork_child_process(void)
  198. {
  199.         pid_t pid;
  200.         int status;

  201.         if (!(pid = fork())) {
  202.                 switch (fork()) {
  203.                         case 0:
  204.                                 return 0;
  205.                         case -1:
  206.                                 _exit(errno);
  207.                         default:
  208.                                 _exit(0);
  209.                 }
  210.         }
  211.         
  212.         printf("fork_child_process() function in Parent ");
  213.         
  214.         if (pid < 0 || waitpid(pid, &status, 0) < 0)
  215.                 return -1;

  216.         if (WIFEXITED(status)) {
  217.                 if (WEXITSTATUS(status) == 0)
  218.                         return 1;
  219.                 else
  220.                         errno = WEXITSTATUS(status);
  221.         } else
  222.                 errno = EINTR;

  223.         return -1;
  224. }
  225. void listen_elevators_request()
  226. {
  227.         int sockfd;
  228.         int clientfd;
  229.         pid_t child_id;

  230.         do {
  231.                 sockfd = server_socket(5);
  232.         } while (sockfd < 0);

  233.         while (1)
  234.         {
  235.                 printf("elevators_server_socket: %d \n", sockfd);
  236.                 
  237.                 clientfd = elevator_accept_socket(sockfd);
  238.                 
  239.                 if (clientfd == -1) {
  240.                         printf("no elevator to connect to server\n");
  241.                         continue;
  242.                 }
  243.                 
  244.                 printf("elevator client connect to server succecfully !\n");
  245.                 printf("elevator the current data socket is :%d \n", clientfd);
  246.                 
  247.                 if ((child_id = fork_child_process()) == 0) {
  248.                         printf("elevator server child process created. pid is %d , connecting socket is %d\n",
  249.                                         getpid(), clientfd);
  250.                         Dispatchercmd(clientfd);
  251.                         printf("elevator clientfd = %d exit\n", clientfd);
  252.                         exit(0);
  253.                 } else
  254.                         close(clientfd);

  255.         }
  256.         close(sockfd);
  257. }
  258. int main()
  259. {
  260.         pthread_t thread_Id;
  261.         
  262.         printf("Elevator service: begin Initializing ..... \n");

  263.         if (check_elevator_service_process() == 1) {
  264.                 printf("Elevator service process already running, exiting elevator service!\n");
  265.                 exit(1);
  266.         }
  267.         
  268.         if (record_elevator_service_process() == 0) {
  269.                 printf("Error writing pid to file, exiting elevator service!\n");
  270.                 printf("Writing PID failed\n");
  271.                 exit(1);
  272.         }
  273.         
  274.         printf("Elevator service: end Initializing ..... \n");
  275.         
  276.         if (!pthread_create(&thread_Id, NULL, (void *) &listen_elevators_request, NULL)) {
  277.                 pthread_detach(thread_Id);
  278.                 printf("Linste thread has been created!");
  279.         }
  280.         else
  281.                 printf("could not create thread!");

  282.         while (1)
  283.                 sleep(10);

  284.         printf("Elevator service code should not arrive here!");
  285.         return 0;
  286. }
这个是client的代码

点击(此处)折叠或打开

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <pthread.h>

  7. #include <sys/file.h>
  8. #include <sys/stat.h>
  9. #include <sys/types.h>
  10. #include <sys/socket.h>

  11. #include <netinet/in.h>
  12. #include <arpa/inet.h>

  13. enum elevator_status {
  14.         idle = 1, up, down
  15. };

  16. typedef struct {
  17.         int name; //Name
  18.         enum elevator_status status; //Status
  19.         int position; //Number of floor
  20.         struct tm * open_time; //Bootup time
  21.         struct tm * close_time; //Close time
  22.         struct tm * run_time; //Running time
  23.         struct tm * idle_time; //Idle time
  24. } elevator_class;

  25. static const char *client_num_file = "/tmp/elevator_client.num";
  26. elevator_class elevator;

  27. int read_num_file(const char *num_file)
  28. {
  29.         FILE *f;
  30.         int num = 0;

  31.         if ((f = fopen(num_file, "r")) != NULL) {
  32.                 fscanf(f, "%d", &num);
  33.                 fclose(f);
  34.         }
  35.         return (num);
  36. }
  37. int check_elevator_clinet_num()
  38. {
  39.         int client_num = read_num_file(client_num_file);
  40.         
  41.         if (client_num == 0)
  42.                 client_num = 1;
  43.         else
  44.                 client_num++;
  45.         
  46.         return client_num;
  47. }

  48. int record_elevator_client_num()
  49. {
  50.         FILE *fp;
  51.         int client_num = 0;
  52.         char str[2] = {'\0'};

  53.         client_num = check_elevator_clinet_num();
  54.         
  55.         if ((fp = fopen(client_num_file, "w+")) != NULL) {
  56.                         sprintf(str, "%d", client_num);
  57.                         if (fwrite(str, sizeof(str), 1, fp) <= 0)
  58.                                 printf("record elevator client faile!\n");
  59.                 fclose(fp);
  60.         }
  61.         return client_num;
  62. }
  63. int client_socket()
  64. {
  65.         int cfd;
  66.         
  67.         cfd = socket(AF_INET, SOCK_STREAM, 0);
  68.         
  69.         if(cfd == -1)
  70.         {
  71.                 printf("socket fail ! \r\n");
  72.                 return -1;
  73.         }
  74.         
  75.         return cfd;
  76. }

  77. int client_connect(int cfd)
  78. {
  79.         struct sockaddr_in s_add;
  80.         unsigned short portnum = 0x8888;
  81.         
  82.         bzero(&s_add,sizeof(struct sockaddr_in));
  83.         s_add.sin_family=AF_INET;
  84.         s_add.sin_addr.s_addr= inet_addr("127.0.0.1");
  85.         s_add.sin_port=htons(portnum);
  86.         
  87.         if(connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)) == -1)
  88.         {
  89.                 printf("connect fail !\r\n");
  90.                 return -1;
  91.         }

  92.         return 1;
  93. }

  94. int recv_socket(int sockfd, void *buffer, int size)
  95. {
  96.         int result = -1;
  97.         
  98.         result = recv(sockfd, buffer, size, MSG_WAITALL);
  99.         
  100.         if (result == -1) {
  101.                 printf("there is no data to receive \n");
  102.         }
  103.         
  104.         return result;
  105. }
  106. int send_socket(int sockfd, void *buffer, int size)
  107. {
  108.         int result = -1;
  109.         
  110.         result = send(sockfd, buffer, size, MSG_DONTWAIT);
  111.         
  112.         if (result == -1) {
  113.                 printf("there is no data to receive \n");
  114.         }
  115.         
  116.         return result;
  117. }
  118. void listen_user_request()
  119. {
  120.         int num;
  121.         int lenth = 0;
  122.         int sockfd;
  123.         char res[2];
  124.         
  125.         printf("listen_user_request start ...\n");

  126.         while (1) {
  127.                 
  128.                 do {
  129.                         sockfd = client_socket();
  130.                 } while (sockfd < 0);

  131.                 if (client_connect(sockfd) == -1)
  132.                 {
  133.                         sleep(1);
  134.                         continue;
  135.                 }
  136.                 
  137.                 printf("please input num : \n");
  138.                 scanf("%d", &num);
  139.                 
  140.                 lenth = send_socket(sockfd, &num, sizeof(int));
  141.                 
  142.                 if (lenth == -1) {
  143.                         printf("The send num faile\n");
  144.                         close(sockfd);
  145.                         continue;
  146.                 }
  147.                 
  148.                 lenth = recv_socket(sockfd, res, 3);
  149.                 
  150.                 if (lenth == -1) {
  151.                         printf("The recv faile\n");
  152.                         close(sockfd);
  153.                         continue;
  154.                 }
  155.                 
  156.                 if (strcmp("OK", res)) {
  157.                         close(sockfd);
  158.                         continue;
  159.                 }

  160.                 printf("%s\n", res);
  161.                 
  162.                 lenth = send_socket(sockfd, &elevator, sizeof(elevator_class));
  163.                 
  164.                 if (lenth == -1) {
  165.                         printf("The send elevator_status faile\n");
  166.                         close(sockfd);
  167.                         continue;
  168.                 }
  169.                 
  170.                 lenth = recv_socket(sockfd, res, 4);
  171.                 
  172.                 if (lenth == -1) {
  173.                         printf("The recv faile\n");
  174.                         close(sockfd);
  175.                         continue;
  176.                 }
  177.                 
  178.                 if (strcmp("Run", res)) {
  179.                         close(sockfd);
  180.                         continue;
  181.                 }
  182.                 printf("%s\n", res);
  183.                 printf("The %d elevator start run!\n", elevator.name);
  184.                 close(sockfd);
  185.         }
  186. }

  187. struct tm * get_current_time()
  188. {
  189.         time_t rawtime;
  190.         struct tm * timeinfo;

  191.         time(&rawtime); /* get the current time */
  192.         timeinfo = localtime(&rawtime);

  193.         printf("The current time is: %s\n", asctime(timeinfo));
  194.         printf("%4d-%02d-%02d %02d:%02d:%02d\n",
  195.                         1900+timeinfo->tm_year, /* year */
  196.                         1+timeinfo->tm_mon, /* month */
  197.                         timeinfo->tm_mday, /* date */
  198.                         timeinfo->tm_hour, /* hour */
  199.                         timeinfo->tm_min, /* minute */
  200.                         timeinfo->tm_sec); /* second */

  201.         return timeinfo;
  202. }
  203. int main()
  204. {
  205.         pthread_t thread_Id;
  206.         printf("Elevator clients: begin Initializing ..... \n");
  207.         
  208.         int client_num = record_elevator_client_num();
  209.         
  210.         if (client_num == 0)
  211.                 printf("Error get elevator client num to file!\n");

  212.         elevator.name = client_num;
  213.         elevator.status = idle;
  214.         elevator.open_time = get_current_time();
  215.         elevator.close_time = 0;
  216.         elevator.run_time = 0;
  217.         elevator.idle_time = 0;

  218.         if (!pthread_create(&thread_Id, NULL, (void *) &listen_user_request, NULL)) {
  219.                 pthread_detach(thread_Id);
  220.                 printf("Linste thread has been created!");
  221.         }
  222.         else
  223.                 printf("could not create thread!");

  224.         while (1)
  225.                 sleep(10);

  226. }

需要添加的功能:server上的判断算法,client端的client的数量需要通过server传送过来,还有client的执行工作的顺序。以后有时间慢慢添加。
主要熟悉下stock的编程,顺便练练手再,老不写代码手的生疏了
阅读(1868) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~