Пример #1
0
function httpGet($host, $base_fd)
{
    global $index;
    $fd = stream_socket_client("{$host}", $errno, $errstr, 3, STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT);
    $index[$fd] = 0;
    $event_fd = event_new();
    event_set($event_fd, $fd, EV_WRITE | EV_PERSIST, function ($fd, $events, $arg) use($host) {
        global $times, $limit, $index;
        if (!$index[$fd]) {
            $index[$fd] = 1;
            $out = "GET / HTTP/1.1\r\n";
            $out .= "Host: {$host}\r\n";
            $out .= "Connection: Close\r\n\r\n";
            fwrite($fd, $out);
        } else {
            $str = fread($fd, 4096);
            echo $str, PHP_EOL;
            if (feof($fd)) {
                fclose($fd);
                $times++;
                echo "done\n";
                if ($times == $limit - 1) {
                    event_base_loopexit($arg[1]);
                }
            }
        }
    }, array($event_fd, $base_fd));
    event_base_set($event_fd, $base_fd);
    event_add($event_fd);
}
Пример #2
0
function user_login($mysqli, $login, $password)
{
    // Получим данные пользователя
    $user_data = user_get_data_by_login($mysqli, $login);
    // Сравниваем пароли
    if ($user_data['password'] === md5(md5($password))) {
        // Пароли сошлись
        // Генерируем случайное число и шифруем его
        $hash = md5(generate_code(10));
        // Запрос
        $query = "UPDATE users SET hash='{$hash}' WHERE id='{$user_data['id']}'";
        // Записываем в БД новый хеш авторизации и ID
        if ($result = $mysqli->query($query)) {
            // Запись прошла успешно
            // Запишем событие в журнал
            event_add($mysqli, 15, "Пользователь принял смену.", $_POST['login']);
            // Запишем в куки id
            setcookie("id", $user_data['id'], time() + 60 * 60 * 24 * 30);
            // и хэш
            setcookie("hash", $hash, time() + 60 * 60 * 24 * 30);
            // Переадресовываем на главную
            header("Location: index.php");
            exit;
            // Сообщим об успешном входе
            return "Добро пожаловать";
        }
        return "Ошибка записи в БД";
    } else {
        return "Неправильная комбинация имени пользователя и пароля";
    }
}
 public function __construct($port)
 {
     global $errno, $errstr;
     if (!extension_loaded('libevent')) {
         die("Please install libevent extension firstly\n");
     }
     if ($port < 1024) {
         die("Port must be a number which bigger than 1024\n");
     }
     $socket_server = stream_socket_server("tcp://0.0.0.0:{$port}", $errno, $errstr);
     if (!$socket_server) {
         die("{$errstr} ({$errno})");
     }
     stream_set_blocking($socket_server, 0);
     // 非阻塞
     // event_base_new — Create and initialize new event base
     $base = event_base_new();
     // event_new — Create new event
     $event = event_new();
     // event_set — Prepare an event
     event_set($event, $socket_server, EV_READ | EV_PERSIST, [__CLASS__, 'ev_accept'], $base);
     // event_base_set — Associate event base with an event
     event_base_set($event, $base);
     // event_add — Add an event to the set of monitored events
     event_add($event);
     // event_base_loop — Handle events
     event_base_loop($base);
     self::$connections = [];
     self::$buffers = [];
 }
 public function request($method = null)
 {
     if (!$this->uri instanceof Zend_Uri_Http) {
         /** @see Zend_Http_Client_Exception */
         require_once 'Zend/Http/Client/Exception.php';
         throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
     }
     if ($method) {
         error_log('aaa');
         $this->setMethod($method);
     }
     $uri = $this->uri;
     $port = isset($tmp['port']) ? $tmp['port'] : 80;
     $host = $uri->getHost();
     $port = $uri->getPort();
     $socket = stream_socket_client("{$host}:{$port}", $errno, $errstr, (int) $this->config['timeout'], STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT);
     stream_set_blocking($socket, 0);
     $base = $this->config['eventbase'];
     $writeEvent = event_new();
     event_set($writeEvent, $socket, EV_WRITE, array($this, 'onAccept'), array($writeEvent, $base));
     event_base_set($writeEvent, $base);
     event_add($writeEvent);
     $readEvent = event_new();
     event_set($readEvent, $socket, EV_READ | EV_PERSIST, array($this, 'onRead'), array($readEvent, $base));
     event_base_set($readEvent, $base);
     event_add($readEvent);
     if (!empty($callback)) {
         $this->callback = $callback;
     }
 }
Пример #5
0
 public function getProcess()
 {
     if (!$this->process) {
         $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
         $cmd = PHPBIN . ' -f ' . realpath(__DIR__ . '/../bin/') . '/worker.php';
         $this->process = proc_open($cmd, $descriptorspec, $pipes, '/tmp', array('prefix' => $this->parent->prefix, 'bootstrap' => $this->parent->script, 'verbose' => VERBOSE));
         if ($this->process === false) {
             $error = error_get_last();
             $this->parent->log('Error : unable to start a process - ' . $error['message']);
         } else {
             $this->std_out = $pipes[0];
             $this->std_in = $pipes[1];
             $this->std_err = $pipes[2];
             stream_set_blocking($this->std_in, 0);
             stream_set_blocking($this->std_err, 0);
             VERBOSE && $this->parent->log('Start a new process : ' . $this->process);
             if (function_exists('event_new')) {
                 $this->event = event_new();
                 event_set($this->event, $this->std_in, EV_READ | EV_PERSIST, array($this, 'onRead'), array($this->event, $this->parent->events));
                 event_base_set($this->event, $this->parent->events);
                 event_add($this->event);
             }
         }
     }
     return $this->process;
 }
Пример #6
0
 function EpollSocketServer($port)
 {
     global $errno, $errstr;
     if (!extension_loaded('libevent')) {
         die("Please install libevent extension firstly/n");
     }
     if ($port < 1024) {
         die("Port must be a number which bigger than 1024/n");
     }
     $socket_server = stream_socket_server("tcp://0.0.0.0:{$port}", $errno, $errstr);
     if (!$socket_server) {
         die("{$errstr} ({$errno})");
     }
     stream_set_blocking($socket_server, 0);
     // 非阻塞
     $base = event_base_new();
     $event = event_new();
     event_set($event, $socket_server, EV_READ | EV_PERSIST, array(__CLASS__, 'ev_accept'), $base);
     event_base_set($event, $base);
     event_add($event);
     event_base_loop($base);
     self::$connections = array();
     self::$buffers = array();
     self::$imei = array();
 }
Пример #7
0
 }
 /**
  * Creates a bufferized stream
  * @return Buffer
  */
 public static function buffer($stream)
 {
     if (is_string($stream)) {
Пример #8
0
 /**
  * Ticks at the specified interval
  */
 public function tick()
 {
     call_user_func_array($this->fn, array($this));
     if (!empty($this->event)) {
         event_add($this->event, $this->interval * 1000);
     }
 }
Пример #9
0
 public function start()
 {
     $this->onStart();
     $this->base = event_base_new();
     if ($this->_server) {
         $this->event = event_new();
         event_set($this->event, $this->_server, EV_READ | EV_PERSIST, array($this, 'accept'), $this->base);
         event_base_set($this->event, $this->base);
         event_add($this->event);
     }
     if ($this->_service) {
         $this->service_event = event_new();
         event_set($this->service_event, $this->_service, EV_READ | EV_PERSIST, array($this, 'service'), $this->base);
         event_base_set($this->service_event, $this->base);
         event_add($this->service_event);
     }
     if ($this->_master) {
         $this->master_event = event_new();
         event_set($this->master_event, $this->_master, EV_READ | EV_PERSIST | EV_WRITE, array($this, 'master'), $this->base);
         event_base_set($this->master_event, $this->base);
         event_add($this->master_event);
     }
     if ($this->timer) {
         $timer = event_timer_new();
         event_timer_set($timer, array($this, '_onTimer'), $timer);
         event_base_set($timer, $this->base);
         //event_timer_pending($timer, $this->timer * 1000000);
         event_timer_add($timer, $this->timer * 1000000);
     }
     event_base_loop($this->base);
 }
Пример #10
0
 public function timeout($timeout = null)
 {
     if ($timeout !== null) {
         $this->lastTimeout = $timeout;
     }
     event_add($this->ev, $this->lastTimeout);
 }
Пример #11
0
 private function sleep($sec = null)
 {
     if ($sec !== null) {
         $this->lastSleepSec = $sec;
     }
     event_add($this->ev, $this->lastSleepSec * 1000 * 1000);
 }
Пример #12
0
 public function start()
 {
     self::$_logger->info('Server starts.');
     // Init a non-blocking TCP socket for listening
     $this->_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if (!$this->_sock) {
         $errno = socket_last_error();
         $errstr = socket_strerror($errno);
         self::$_logger->err("Socket create error: {$errstr} ({$errno})");
         die;
     }
     socket_set_nonblock($this->_sock);
     if (!socket_bind($this->_sock, $this->_addr, $this->_port)) {
         $errno = socket_last_error();
         $errstr = socket_strerror($errno);
         self::$_logger->err("Socket bind error: {$errstr} ({$errno})");
         die;
     }
     if (!socket_listen($this->_sock, $this->_listenQueue)) {
         $errno = socket_last_error();
         $errstr = socket_strerror($errno);
         self::$_logger->err("Socket listen error: {$errstr} ({$errno})");
         die;
     }
     // For the listening socket, we use raw event to handle it.
     $this->_listenEvent = event_new();
     event_set($this->_listenEvent, $this->_sock, EV_READ | EV_PERSIST, array($this, 'handleAcceptEvent'));
     event_base_set($this->_listenEvent, $this->_eventBase);
     event_add($this->_listenEvent);
     // Endless loop
     $this->_started = TRUE;
     event_base_loop($this->_eventBase);
     // The loop ends here.
     $this->stop();
 }
 public function start()
 {
     $this->base = event_base_new();
     if ($this->_server) {
         $this->event = event_new();
         event_set($this->event, $this->_server, EV_READ | EV_PERSIST, array($this, 'accept'), $this->base);
         event_base_set($this->event, $this->base);
         event_add($this->event);
     }
     foreach ($this->_services as $serviceId => $service) {
         $event = event_new();
         event_set($event, $service, EV_READ | EV_PERSIST | EV_WRITE, array($this, 'service'), $this->base);
         event_base_set($event, $this->base);
         event_add($event);
         $this->events[$serviceId] = $event;
     }
     if ($this->timer) {
         $timer = event_timer_new();
         event_timer_set($timer, array($this, '_onTimer'), $timer);
         event_base_set($timer, $this->base);
         //event_timer_pending($timer, $this->timer * 1000000);
         event_timer_add($timer, $this->timer * 1000000);
     }
     event_base_loop($this->base);
 }
Пример #14
0
 public function onAcceptEvent($bindSocket, $events, $arg)
 {
     $bindSocketId = $arg[0];
     Debug::netEvent(get_class($this) . '::' . __METHOD__ . '(' . $bindSocketId . ') invoked.');
     // add to accept next event
     // why not use EV_PERSIST
     event_add($this->bindSocketEvPool[$bindSocketId]);
     $connSocket = stream_socket_accept($this->bindSocketPool[$bindSocketId]);
     if (!$connSocket) {
         Debug::netErrorEvent(get_class($this) . ': can not accept new TCP-socket');
         return;
     }
     stream_set_blocking($connSocket, 0);
     list($ip, $port) = explode(':', stream_socket_get_name($connSocket, true));
     $connId = daemon::getNextConnId();
     $evBuf = event_buffer_new($connSocket, array($this, 'onEvBufReadEvent'), array($this, 'onEvBufWriteEvent'), array($this, 'onEventEvent'), array($connId));
     event_buffer_base_set($evBuf, daemon::$eventBase);
     event_buffer_priority_set($evBuf, 10);
     event_buffer_watermark_set($evBuf, EV_READ, $this->evBufLowMark, $this->evBufHighMark);
     if (!event_buffer_enable($evBuf, EV_READ | EV_WRITE | EV_PERSIST)) {
         Debug::netErrorEvent(get_class($this) . '::' . __METHOD__ . ': can not set base of buffer. #' . $connId);
         //close socket
         stream_socket_shutdown($connSocket, STREAM_SHUT_RDWR);
         fclose($connSocket);
         return;
     }
     // 调试这里时,浪费了很多时间,必须注意的是,以上 event 所用的变量如果在函数中,如果没有交给其他的变量引用,在函数结束时就会销毁,
     // 造成连接直接断或者bufferevent 不能触发。晕啊晕。
     $this->connSocketPool[$connId] = $connSocket;
     $this->connEvBufPool[$connId] = $evBuf;
     $this->updateLastContact($connId);
     $this->onAccepted($connId, $ip, $port);
 }
Пример #15
0
 public function connectTo($host, $port, $blockConnect = false)
 {
     Debug::netEvent(get_class($this) . '::' . __METHOD__ . '(' . $host . ':' . $port . ') invoked.');
     $connSocket = stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, 30);
     //add err connect
     stream_set_blocking($connSocket, 0);
     if (!is_resource($connSocket)) {
         Debug::netErrorEvent(get_class($this) . ': can not add errorneus socket with address \'' . $host . ':' . $port . '\'.');
         return false;
     }
     $connId = daemon::getNextSocketId();
     //@todo 增加阻塞 connect , 这样可以返回 connId 的时候 socketSession 已经建立好
     if ($blockConnect) {
     }
     $ev = event_new();
     // why not use EV_PERSIST, is because first event is acceptEvent?
     if (!event_set($ev, $connSocket, EV_WRITE, array($this, 'onConnectedEvent'), array($connId))) {
         Debug::netErrorEvent(get_class($this) . '::' . __METHOD__ . ': can not set onAcceptEvent() on binded socket: ' . Debug::dump($connSocket));
         return false;
     }
     event_base_set($ev, daemon::$eventBase);
     event_add($ev, 1 * 1000 * 1000);
     $this->checkConnSocketPool[$connId] = $connSocket;
     $this->checkConnEvPool[$connId] = $ev;
     return $connId;
 }
Пример #16
0
 public function addWriteStream($stream, $listener)
 {
     $event = event_new();
     event_set($event, $stream, EV_READ | EV_PERSIST, $listener);
     event_base_set($event, $this->base);
     event_add($event);
     $this->events[(int) $stream] = $event;
 }
Пример #17
0
 /**
  * Add signal handler.
  *
  * @param $signal
  * @param $callback
  * @return bool
  */
 public function addSignal($signal, $callback)
 {
     $event = event_new();
     $this->_signalEvents[$signal] = $event;
     event_set($event, $signal, EV_SIGNAL | EV_PERSIST, $callback);
     event_base_set($event, $this->_eventBase);
     event_add($event);
 }
 public function onConnect()
 {
     $clientSocket = stream_socket_accept($this->handle_);
     stream_set_blocking($clientSocket, 0);
     $clientEvent = event_new();
     \event_set($clientEvent, $clientSocket, EV_READ | EV_PERSIST, array($this, 'onRequest'), array($clientEvent));
     \event_base_set($clientEvent, $this->base_);
     event_add($clientEvent);
 }
Пример #19
0
 public function setTimeout($callback, $interval_ms)
 {
     $base = \Event\Emitter::getBase();
     $event = event_timer_new();
     $arg = array($callback, $event, $interval_ms);
     event_timer_set($event, array($this, 'ev_timer'), $arg);
     event_base_set($event, $base);
     event_add($event, $interval_ms * 1000);
 }
Пример #20
0
function accept_cb($socket, $flag, $base)
{
    $conn = stream_socket_accept($socket, 0);
    stream_set_blocking($conn, 0);
    $event = event_new();
    event_set($event, $conn, EV_READ | EV_PERSIST, read_cb, $base);
    event_base_set($event, $base);
    event_add($event);
}
Пример #21
0
 function add($event)
 {
     $ev = event_new();
     event_set($ev, $event->fd, $event->events, function () use($event) {
         call_user_func($event->callback, $event);
     });
     event_base_set($ev, $this->handle);
     event_add($ev);
     $event->base = $this;
     $event->handle = $ev;
     return $this;
 }
Пример #22
0
 /**
  * @param \Icicle\Loop\LoopInterface $loop
  * @param \Icicle\Loop\Events\EventFactoryInterface $factory
  * @param resource $base
  */
 public function __construct(LibeventLoop $loop, EventFactoryInterface $factory)
 {
     parent::__construct($loop, $factory);
     $callback = $this->createSignalCallback();
     $base = $loop->getEventBase();
     foreach ($this->getSignalList() as $signo) {
         $event = event_new();
         event_set($event, $signo, EV_SIGNAL | EV_PERSIST, $callback);
         event_base_set($event, $base);
         event_add($event);
         $this->events[$signo] = $event;
     }
 }
Пример #23
0
 /**
  * 运行服务器程序
  * @return unknown_type
  */
 function run()
 {
     //初始化事件系统
     $this->init();
     //建立服务器端Socket
     $this->server_sock = $this->create("udp://{$this->host}:{$this->port}");
     //设置事件监听,监听到服务器端socket可读,则有连接请求
     event_set($this->server_event, $this->server_sock, EV_READ | EV_PERSIST, "sw_server_handle_recvfrom", $this);
     event_base_set($this->server_event, $this->base_event);
     event_add($this->server_event);
     $this->protocol->onStart();
     event_base_loop($this->base_event);
 }
Пример #24
0
 public function __construct($address, $port)
 {
     $this->base = event_base_new();
     $this->event = event_new();
     Logger::getInstance()->outString("Create new socket for " . $address . ":" . $port);
     $errno = 0;
     $errstr = '';
     $socket = stream_socket_server('tcp://' . $address . ':' . $port, $errno, $errstr);
     stream_set_blocking($socket, 0);
     event_set($this->event, $socket, EV_READ | EV_PERSIST, array($this, 'accept'), $this->base);
     event_base_set($this->event, $this->base);
     event_add($this->event);
     $this->onLoad();
 }
Пример #25
0
 /**
  * Register signals.
  * @return void
  */
 public function registerEventSignals()
 {
     foreach (self::$signals as $no => $name) {
         if ($name === 'SIGKILL' || $name == 'SIGSTOP') {
             continue;
         }
         $ev = event_new();
         if (!event_set($ev, $no, EV_SIGNAL | EV_PERSIST, array($this, 'eventSighandler'), array($no))) {
             throw new Exception('Cannot event_set for ' . $name . ' signal');
         }
         event_base_set($ev, $this->eventBase);
         event_add($ev);
         $this->sigEvents[$no] = $ev;
     }
 }
 protected function addSocketEvent()
 {
     $event = event_new();
     if (!event_set($event, $this->socket, EV_READ | EV_PERSIST, array($this, 'onEventAccept'))) {
         throw new RuntimeException("Can't set event");
     }
     if (false === event_base_set($event, $this->event_base)) {
         throw new RuntimeException("Can't set [{$socket_num}] event base.");
     }
     if (false === event_add($event)) {
         throw new RuntimeException("Can't add event");
     }
     $this->socket_events = $event;
     self::log('Socket', 'event added');
 }
Пример #27
0
 public function start()
 {
     $n = 0;
     foreach ($this->fds as $fd) {
         ++$n;
         $event = 'event#' . $n;
         stream_set_blocking($fd, 0);
         $event = event_new();
         event_set($event, $fd, EV_READ | EV_PERSIST, $this->eventcb[(int) $fd], $this->ev_base);
         event_base_set($event, $this->ev_base);
         event_add($event);
         $this->events[] = $event;
     }
     $this->run();
 }
Пример #28
0
 public static function initEvent()
 {
     if (!self::$supported) {
         return;
     }
     self::updateConfig();
     self::$ev = event_new();
     self::$fd = eio_get_event_stream();
     event_set(self::$ev, self::$fd, EV_READ | EV_PERSIST, function ($fd, $events, $arg) {
         if (eio_nreqs()) {
             eio_poll();
         }
     });
     event_base_set(self::$ev, Daemon::$process->eventBase);
     event_add(self::$ev);
 }
Пример #29
0
 public function listen()
 {
     if (!$this->client_type) {
         throw new \Exception('Client type was not defined, please call setClientType() with the type of client (ie \\Beehive\\Clients\\Telnet) before listen()');
     }
     if (!is_callable($this->read_callback)) {
         throw new \Exception('Read callback is not defined with a valid callback, please call setReadCallback() with a valid callback');
     }
     $this->connection = stream_socket_server('tcp://' . $this->host . ':' . $this->port, $errno, $errstr);
     stream_set_blocking($this->connection, 0);
     $event = event_new();
     event_set($event, $this->connection, EV_READ | EV_PERSIST, [$this, 'addClient'], $this->event_base);
     event_base_set($event, $this->event_base);
     event_add($event);
     event_base_loop($this->event_base);
 }
Пример #30
0
 /**
  * 运行服务器程序
  * @return unknown_type
  */
 function run($num = 1)
 {
     //初始化事件系统
     if (!$this->protocol instanceof Swoole_TCP_Server_Protocol) {
         return error(902);
     }
     $this->init();
     //建立服务器端Socket
     $this->server_sock = $this->create("tcp://{$this->host}:{$this->port}");
     //设置事件监听,监听到服务器端socket可读,则有连接请求
     event_set($this->server_event, $this->server_sock, EV_READ | EV_PERSIST, "sw_server_handle_connect", $this);
     event_base_set($this->server_event, $this->base_event);
     event_add($this->server_event);
     if ($num - 1 > 0) {
         sw_spawn($num - 1);
     }
     $this->protocol->onStart();
     event_base_loop($this->base_event);
 }