Chinaunix首页 | 论坛 | 博客
  • 博客访问: 909988
  • 博文数量: 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-09-05 16:45:21


点击(此处)折叠或打开

  1. <?php
  2. $socket = stream_socket_server ('tcp://127.0.0.1:6666', $errno, $errstr);
  3. stream_set_blocking($socket, 0);
  4. $works = $GLOBALS['connections'] = $GLOBALS['buffers'] = array();
  5. for ( $i = 0 ; $i <= 1; $i++) {
  6.         $pid = pcntl_fork();
  7.         if ($pid == -1)
  8.         {
  9.                 die("fork(1) failed!\n");
  10.         }
  11.         elseif ($pid > 0)
  12.         {
  13.           $works[$pid] = $pid;
  14.         } elseif( $pid == 0 ) {
  15.                 $base = event_base_new();
  16.                 $event = event_new();
  17.                 event_set($event, $socket, EV_READ | EV_PERSIST, 'ev_accept', $base);
  18.                 event_base_set($event, $base);
  19.                 event_add($event);
  20.                 event_base_loop($base);
  21.         }
  22. }
  23. function ev_accept($socket, $flag, $base) {
  24.     static $id = 0;
  25.     $connection = @stream_socket_accept($socket,0);
  26.     if( $connection === false ) {
  27.       return ;
  28.     }
  29.     stream_set_blocking($connection, 0);

  30.     $id += 1;

  31.     $buffer = event_buffer_new($connection, 'ev_read', NULL, 'ev_error', $id);
  32.     event_buffer_base_set($buffer, $base);
  33.     event_buffer_timeout_set($buffer, 30, 30);
  34.     event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff);
  35.     event_buffer_priority_set($buffer, 10);
  36.     event_buffer_enable($buffer, EV_READ | EV_PERSIST);

  37.     // we need to save both buffer and connection outside
  38.     $GLOBALS['connections'][$id] = $connection;
  39.     $GLOBALS['buffers'][$id] = $buffer;
  40. }
  41. function ev_error($buffer, $error, $id) {
  42.     event_buffer_disable($GLOBALS['buffers'][$id], EV_READ | EV_WRITE);
  43.     event_buffer_free($GLOBALS['buffers'][$id]);
  44.     fclose($GLOBALS['connections'][$id]);
  45.     unset($GLOBALS['buffers'][$id], $GLOBALS['connections'][$id]);
  46. }

  47. function ev_read($buffer, $id) {
  48.     while ($read = event_buffer_read($buffer, 256)) {
  49.         foreach( $GLOBALS['connections'] as $ids => $conn ) {
  50.                 if( $ids != $id ) {
  51.                         fwrite($conn,$read);
  52.                 }
  53.         }
  54.     }
  55. }
  56. while (1) {
  57.    pcntl_signal_dispatch();
  58.    $status = 0;
  59.    $pid = pcntl_wait($status, WUNTRACED);
  60.    pcntl_signal_dispatch();

  61.    if ($pid > 0) {
  62.      echo "{$pid}进程结束";
  63.    }
  64. }
  65. ?>

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