Exemples

Exemple #1 Surveillance de STDIN en utilisant l'API basique

<?php

function print_line($fd$events$arg)
{
    static 
$max_requests 0;

    
$max_requests++;

    if (
$max_requests == 10) {
        
// Sort de la boucle après 10 écritures
        
event_base_loopexit($arg[1]);
    }

    
// Affiche la ligne
    
echo  fgets($fd);
}

// Création de la base et de l'événement
$base event_base_new();
$event event_new();

$fd STDIN;

// Définit les drapeaux de l'événement
event_set($event$fdEV_READ EV_PERSIST"print_line", array($event$base));
// Définit la base de l'événement
event_base_set($event$base);

// Activation de l'événement
event_add($event);
// Début de la boucle de l'événement
event_base_loop($base);

?>

Exemple #2 Surveillance de STDIN en utilisant l'API des événements mis en tampon

<?php

function print_line($buf$arg)
{
    static 
$max_requests;

    
$max_requests++;

    if (
$max_requests == 10) {
        
event_base_loopexit($arg);
    }

    
// Affiche la ligne
    
echo event_buffer_read($buf4096);
}

function 
error_func($buf$what$arg)
{
    
// Gestion de l'erreur
}

$base event_base_new();
$eb event_buffer_new(STDIN"print_line"NULL,  "error_func"$base);

event_buffer_base_set($eb,  $base);
event_buffer_enable($eb,  EV_READ);

event_base_loop($base);

?>

add a note add a note

User Contributed Notes 1 note

up
3
Alexis
14 years ago
Server example:
<?php
$socket
= stream_socket_server ('tcp://0.0.0.0:2000', $errno, $errstr);
stream_set_blocking($socket, 0);
$base = event_base_new();
$event = event_new();
event_set($event, $socket, EV_READ | EV_PERSIST, 'ev_accept', $base);
event_base_set($event, $base);
event_add($event);
event_base_loop($base);

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

function
ev_accept($socket, $flag, $base) {
    static
$id = 0;
   
   
$connection = stream_socket_accept($socket);
   
stream_set_blocking($connection, 0);
   
   
$id += 1;
   
   
$buffer = event_buffer_new($connection, 'ev_read', NULL, 'ev_error', $id);
   
event_buffer_base_set($buffer, $base);
   
event_buffer_timeout_set($buffer, 30, 30);
   
event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff);
   
event_buffer_priority_set($buffer, 10);
   
event_buffer_enable($buffer, EV_READ | EV_PERSIST);
   
   
// we need to save both buffer and connection outside
   
$GLOBALS['connections'][$id] = $connection;
   
$GLOBALS['buffers'][$id] = $buffer;
}

function
ev_error($buffer, $error, $id) {
   
event_buffer_disable($GLOBALS['buffers'][$id], EV_READ | EV_WRITE);
   
event_buffer_free($GLOBALS['buffers'][$id]);
   
fclose($GLOBALS['connections'][$id]);
    unset(
$GLOBALS['buffers'][$id], $GLOBALS['connections'][$id]);
}

function
ev_read($buffer, $id) {
    while (
$read = event_buffer_read($buffer, 256)) {
       
var_dump($read);
    }
}
?>
To Top