Chinaunix首页 | 论坛 | 博客
  • 博客访问: 756002
  • 博文数量: 96
  • 博客积分: 2023
  • 博客等级: 上尉
  • 技术积分: 1738
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-15 10:03
文章分类

全部博文(96)

文章存档

2014年(11)

2012年(85)

分类:

2012-04-24 16:49:31

面向连接的socket通信就像与对方打电话,首先需要通过电话建立一个连接,连接建立好之后,彼此才能双向通信。它有几个关键步骤

服务器端通常以守护进程的方式实现:
1: 创建守护进程
2:获取或注册服务
3:创建socket并绑定地址
4:开始监听
5:接收客户端连接请求
6:进行数据传输

客户端
1:获取或注册服务
2:创建socket
3:发送连接请求

示例代码
服务器端的实现(以端口的形式提供给用户使用)

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <netdb.h>
  4. #include <arpa/inet.h>
  5. #include <stddef.h>        /* for offsetof */
  6. #include <string.h>        /* for convenience */
  7. #include <unistd.h>        /* for convenience */
  8. #include <signal.h>        /* for SIG_ERR */

  9. #include <errno.h>
  10. #include <syslog.h>
  11. #include <sys/socket.h>

  12. #include <fcntl.h>
  13. #include <sys/resource.h>

  14. #define BUFLEN    128
  15. #define QLEN 10

  16. #ifndef HOST_NAME_MAX
  17. #define HOST_NAME_MAX 256
  18. #endif

  19. void daemonize(const char *cmd)
  20. {
  21.     int                    i, fd0, fd1, fd2;
  22.     pid_t                pid;
  23.     struct rlimit        rl;
  24.     struct sigaction    sa;

  25.     /*
  26.      * Clear file creation mask.
  27.      */
  28.     umask(0);

  29.     /*
  30.      * Get maximum number of file descriptors.
  31.      */
  32.     if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
  33.         printf("%s: can't get file limit", cmd);

  34.     /*
  35.      * Become a session leader to lose controlling TTY.
  36.      */
  37.     if ((pid = fork()) < 0)
  38.         printf("%s: can't fork", cmd);
  39.     else if (pid != 0) /* parent */
  40.         exit(0);
  41.     setsid();

  42.     /*
  43.      * Ensure future opens won't allocate controlling TTYs.
  44.      */
  45.     sa.sa_handler = SIG_IGN;
  46.     sigemptyset(&sa.sa_mask);
  47.     sa.sa_flags = 0;
  48.     if (sigaction(SIGHUP, &sa, NULL) < 0)
  49.         printf("%s: can't ignore SIGHUP");
  50.     if ((pid = fork()) < 0)
  51.         printf("%s: can't fork", cmd);
  52.     else if (pid != 0) /* parent */
  53.         exit(0);

  54.     /*
  55.      * Change the current working directory to the root so
  56.      * we won't prevent file systems from being unmounted.
  57.      */
  58.     if (chdir("/") < 0)
  59.         printf("%s: can't change directory to /");

  60.     /*
  61.      * Close all open file descriptors.
  62.      */
  63.     if (rl.rlim_max == RLIM_INFINITY)
  64.         rl.rlim_max = 1024;
  65.     for (i = 0; i < rl.rlim_max; i++)
  66.         close(i);

  67.     /*
  68.      * Attach file descriptors 0, 1, and 2 to /dev/null.
  69.      */
  70.     fd0 = open("/dev/null", O_RDWR);
  71.     fd1 = dup(0);
  72.     fd2 = dup(0);

  73.     /*
  74.      * Initialize the log file.
  75.      */
  76.     openlog(cmd, LOG_CONS, LOG_DAEMON);
  77.     if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
  78.         syslog(LOG_ERR, "unexpected file descriptors %d %d %d",
  79.          fd0, fd1, fd2);
  80.         exit(1);
  81.     }
  82. }

  83. int initserver(int type, const struct sockaddr *addr, socklen_t alen,
  84.   int qlen)
  85. {
  86.     int fd;
  87.     int err = 0;

  88.     if ((fd = socket(addr->sa_family, type, 0)) < 0)
  89.         return(-1);
  90.     if (bind(fd, addr, alen) < 0) {
  91.         err = errno;
  92.         goto errout;
  93.     }
  94.     if (type == SOCK_STREAM || type == SOCK_SEQPACKET) {
  95.         if (listen(fd, qlen) < 0) {
  96.             err = errno;
  97.             goto errout;
  98.         }
  99.     }
  100.     return(fd);

  101. errout:
  102.     close(fd);
  103.     errno = err;
  104.     return(-1);
  105. }


  106. void serve(int sockfd)
  107. {
  108.     int        clfd;
  109.     FILE    *fp;
  110.     char    buf[BUFLEN];

  111.     for (;;) {
  112.         clfd = accept(sockfd, NULL, NULL);
  113.         if (clfd < 0) {
  114.             syslog(LOG_ERR, "ruptimed: accept error: %s",
  115.              strerror(errno));
  116.             exit(1);
  117.         }
  118.         if ((fp = popen("/usr/bin/uptime", "r")) == NULL) {
  119.             sprintf(buf, "error: %s\n", strerror(errno));
  120.             send(clfd, buf, strlen(buf), 0);
  121.         } else {
  122.             while (fgets(buf, BUFLEN, fp) != NULL)
  123.                 send(clfd, buf, strlen(buf), 0);
  124.             pclose(fp);
  125.         }
  126.         close(clfd);
  127.     }
  128. }

  129. int main(int argc, char *argv[])
  130. {
  131.     struct addrinfo    *ailist, *aip;
  132.     struct addrinfo    hint;
  133.     int                sockfd, err, n;
  134.     char            *host;

  135.     if (argc != 1)
  136.         printf("usage: ruptimed");
  137. #ifdef _SC_HOST_NAME_MAX
  138.     n = sysconf(_SC_HOST_NAME_MAX);
  139.     if (n < 0)    /* best guess */
  140. #endif
  141.         n = HOST_NAME_MAX;
  142.     host = malloc(n);
  143.     if (host == NULL)
  144.         printf("malloc error");
  145.     if (gethostname(host, n) < 0)
  146.         printf("gethostname error");
  147.     printf("hostname=%s\n",host);

  148.     daemonize("ruptimed");
  149.     hint.ai_flags = AI_PASSIVE;
  150.     hint.ai_family = 0;
  151.     hint.ai_socktype = SOCK_STREAM;
  152.     hint.ai_protocol = 0;
  153.     hint.ai_addrlen = 0;
  154.     hint.ai_canonname = NULL;
  155.     hint.ai_addr = NULL;
  156.     hint.ai_next = NULL;
  157.     if ((err = getaddrinfo(host, "2001", &hint, &ailist)) != 0) {
  158.         syslog(LOG_ERR, "ruptimed: getaddrinfo error: %s",gai_strerror(err));
  159.         exit(1);
  160.     }
  161.     for (aip = ailist; aip != NULL; aip = aip->ai_next) {
  162.         if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr,aip->ai_addrlen, QLEN)) >= 0) {
  163.             printf("initserver ok !\n");
  164.             serve(sockfd);
  165.             exit(0);
  166.         }
  167.     }
  168.     printf("server err !\n");
  169.     exit(1);
  170. }

客户端的实现

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <netdb.h>
  4. #include <arpa/inet.h>
  5. #include <unistd.h>        /* for convenience */

  6. #include <sys/resource.h>
  7. #include <errno.h>
  8. #include <sys/socket.h>

  9. #define MAXADDRLEN    256
  10. #define BUFLEN        128

  11. #define MAXSLEEP 128

  12. int connect_retry(int sockfd, const struct sockaddr *addr, socklen_t alen)
  13. {
  14.     int nsec;

  15.     /*
  16.      * Try to connect with exponential backoff.
  17.      */
  18.     for (nsec = 1; nsec <= MAXSLEEP; nsec <<= 1) {
  19.         if (connect(sockfd, addr, alen) == 0) {
  20.             /*
  21.              * Connection accepted.
  22.              */
  23.             return(0);
  24.         }

  25.         /*
  26.          * Delay before trying again.
  27.          */
  28.         if (nsec <= MAXSLEEP/2)
  29.             sleep(nsec);
  30.     }
  31.     return(-1);
  32. }

  33. void print_uptime(int sockfd)
  34. {
  35.     int        n;
  36.     char    buf[BUFLEN];

  37.     while ((n = recv(sockfd, buf, BUFLEN, 0)) > 0)
  38.         write(STDOUT_FILENO, buf, n);
  39.     if (n < 0)
  40.         printf("recv error");
  41. }

  42. int main(int argc, char *argv[])
  43. {
  44.     struct addrinfo    *ailist, *aip;
  45.     struct addrinfo    hint;
  46.     int                sockfd, err;

  47.     if (argc != 2)
  48.         printf("usage: ruptime hostname");
  49.     hint.ai_flags = AI_CANONNAME;
  50.     hint.ai_family = 0;
  51.     hint.ai_socktype = SOCK_STREAM;
  52.     hint.ai_protocol = 0;
  53.     hint.ai_addrlen = 0;
  54.     hint.ai_canonname = NULL;
  55.     hint.ai_addr = NULL;
  56.     hint.ai_next = NULL;
  57.     if ((err = getaddrinfo(argv[1], "2001", &hint, &ailist)) != 0)
  58.         printf("getaddrinfo error: %s", gai_strerror(err));
  59.     for (aip = ailist; aip != NULL; aip = aip->ai_next) {
  60.         if ((sockfd = socket(aip->ai_family, SOCK_STREAM, 0)) < 0)
  61.             err = errno;
  62.         if (connect_retry(sockfd, aip->ai_addr, aip->ai_addrlen) < 0) {
  63.             err = errno;
  64.         } else {
  65.             print_uptime(sockfd);
  66.             exit(0);
  67.         }
  68.     }
  69.     fprintf(stderr, "can't connect to %s: %s\n", argv[1],strerror(err));
  70.     exit(1);
  71. }

测试流程:服务器端: 修改/etc/hosts如下
192.168.1.11    X64-server
127.0.0.1 localhost
#127.0.1.1       X64-server 

客户端  修改/etc/hosts如下
127.0.0.1 localhost
127.0.1.1 ubuntu
192.168.1.11 X64-server

说明:若服务器端以服务的形式提供给用的使用,服务端和客户端都需要在/etc/services中注册服务,但它们的端口号可以不一样,如:ruptime 2001/tcp,然后将getaddrinfo函数中端口号改为服务名就可以了

面向无连接Socket通信
而向无连接的socket通信就向发电子邮件一样,数据通信之前不需要建立连接的。





 

阅读(855) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~