利用ACL开发并发网络服务器

来源:计算机等级考试    发布时间:2012-08-29    计算机等级考试视频    评论

  1、概述
  本节结合 "利用ACL库开发高并发半驻留式线程池程序" 和 "利用ACL库快速创建你的网络程序" 两篇文章的内容,创建一个简单的线程池网络服务器程序。
  2、并发式网络通信实例
  C代码
  #include "lib_acl.h" /* 先包含ACL库头文件 */
  #include <stdio.h>
  #include <stdlib.h>
  /**
  * 单独的线程处理来自于客户端的连接
  * @param arg {void*} 添加任务时的对象
  */
  static void echo_client_thread(void *arg)
  {
  ACL_VSTREAM *client = (ACL_VSTREAM*) arg;
  char buf[1024];
  int  n;
  /* 设置客户端流的读超时时间为30秒 */
  ACL_VSTREAM_SET_RWTIMO(client, 30);
  /* 循环读客户端的数据,直到其关闭或出错或超时 */
  while (1) {
  /* 等待读客户端发来的数据 */
  n = acl_vstream_read(client, buf, sizeof(buf));
  if (n == ACL_VSTREAM_EOF)
  break;
  /* 将读到的数据写回至客户端流 */
  if (acl_vstream_writen(client, buf, n) == ACL_VSTREAM_EOF)
  break;
  }
  /* 关闭客户端流 */
  acl_vstream_close(client);
  }
  /**
  * 创建半驻留线程池的过程
  * @return {acl_pthread_pool_t*} 新创建的线程池句柄
  */
  static acl_pthread_pool_t *create_thread_pool(void)
  {
  acl_pthread_pool_t *thr_pool; /* 线程池句柄 */
  int max_threads = 100; /* 最多并发100个线程 */
  int idle_timeout = 10; /* 每个工作线程空闲10秒后自动退出 */
  acl_pthread_pool_attr_t attr; /* 线程池初始化时的属性 */
  /* 初始化线程池对象属性 */
  acl_pthread_pool_attr_init(&attr);
  acl_pthread_pool_attr_set_threads_limit(&attr, max_threads);
  acl_pthread_pool_attr_set_idle_timeout(&attr, idle_timeout);
  /* 创建半驻留线程句柄 */
  thr_pool = acl_pthread_pool_create(&attr);
  assert(thr_pool);
  return (thr_pool);
  }
  /**
  * 开始运行
  * @param addr {const char*} 服务器监听地址,如:127.0.0.1:8081
  */
  static void run(const char *addr)
  {
  const char *myname = "run";
  acl_pthread_pool_t *thr_pool;
  ACL_VSTREAM *sstream;
  char ebuf[256];
  thr_pool = create_thread_pool();
  /* 监听一个本地地址 */
  sstream = acl_vstream_listen(addr, 128);
  if (sstream == NULL) {
  printf("%s(%d): listen on %s error(%s)/r/n",
  myname, __LINE__, addr,
  acl_last_strerror(ebuf, sizeof(ebuf)));
  return;
  }

上一页12下一页

视频学习

我考网版权与免责声明

① 凡本网注明稿件来源为"原创"的所有文字、图片和音视频稿件,版权均属本网所有。任何媒体、网站或个人转载、链接转贴或以其他方式复制发表时必须注明"稿件来源:我考网",违者本网将依法追究责任;

② 本网部分稿件来源于网络,任何单位或个人认为我考网发布的内容可能涉嫌侵犯其合法权益,应该及时向我考网书面反馈,并提供身份证明、权属证明及详细侵权情况证明,我考网在收到上述法律文件后,将会尽快移除被控侵权内容。

最近更新

社区交流

考试问答