Chinaunix首页 | 论坛 | 博客
  • 博客访问: 909999
  • 博文数量: 91
  • 博客积分: 803
  • 博客等级: 准尉
  • 技术积分: 1051
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-24 13:42
文章分类

全部博文(91)

文章存档

2021年(1)

2020年(4)

2019年(4)

2018年(9)

2017年(11)

2016年(11)

2015年(6)

2014年(3)

2013年(28)

2012年(14)

分类: PHP

2017-08-23 10:05:48


点击(此处)折叠或打开

  1. <?php
  2. //守护进程化
  3. daemonize();

  4. $socket = stream_socket_server ('tcp://127.0.0.1:9998', $errno, $errstr);
  5. stream_set_blocking($socket, 0);
  6. $base = event_base_new();
  7. $event = event_new();
  8. event_set($event, $socket, EV_READ | EV_PERSIST, 'ev_accept', $base);
  9. event_base_set($event, $base);
  10. event_add($event);
  11. event_base_loop($base);

  12. $GLOBALS['connections'] = array();
  13. $GLOBALS['buffers'] = array();

  14. function ev_accept($socket, $flag, $base) {
  15.     static $id = 0;

  16.     $connection = stream_socket_accept($socket);
  17.     stream_set_blocking($connection, 0);

  18.     $id += 1;

  19.     $buffer = event_buffer_new($connection, 'ev_read', NULL, 'ev_error', $id);
  20.     event_buffer_base_set($buffer, $base);
  21.     event_buffer_timeout_set($buffer, 30, 30);
  22.     event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff);
  23.     event_buffer_priority_set($buffer, 10);
  24.     event_buffer_enable($buffer, EV_READ | EV_PERSIST);

  25.     // we need to save both buffer and connection outside
  26.     $GLOBALS['connections'][$id] = $connection;
  27.     $GLOBALS['buffers'][$id] = $buffer;
  28. }

  29. function ev_error($buffer, $error, $id) {
  30.     event_buffer_disable($GLOBALS['buffers'][$id], EV_READ | EV_WRITE);
  31.     event_buffer_free($GLOBALS['buffers'][$id]);
  32.     fclose($GLOBALS['connections'][$id]);
  33.     unset($GLOBALS['buffers'][$id], $GLOBALS['connections'][$id]);
  34. }

  35. function ev_read($buffer, $id) {
  36.     while ($read = event_buffer_read($buffer, 256)) {
  37.         foreach( $GLOBALS['connections'] as $ids => $conn ) {
  38.                 if( $ids != $id ) {
  39.                         fwrite($conn,$read);
  40.                 }
  41.         }
  42.     }
  43. }


  44. function daemonize()
  45. {
  46.         $pid = pcntl_fork();
  47.         if ($pid == -1)
  48.         {
  49.                 die("fork(1) failed!\n");
  50.         }
  51.         elseif ($pid > 0)
  52.         {
  53.                 //让由用户启动的进程退出
  54.                 exit(0);
  55.         }

  56.         //建立一个有别于终端的新session以脱离终端
  57.         posix_setsid();

  58.         $pid = pcntl_fork();
  59.         if ($pid == -1)
  60.         {
  61.                 die("fork(2) failed!\n");
  62.         }
  63.         elseif ($pid > 0)
  64.         {
  65.                 //父进程退出, 剩下子进程成为最终的独立进程
  66.                 exit(0);
  67.         }
  68. }

  69. ?>

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