本文整理汇总了PHP中event_add函数的典型用法代码示例。如果您正苦于以下问题:PHP event_add函数的具体用法?PHP event_add怎么用?PHP event_add使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了event_add函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: httpGet
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: user_login
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 "Неправильная комбинация имени пользователя и пароля";
}
}
示例3: __construct
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 = [];
}
示例4: request
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: getProcess
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: EpollSocketServer
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: tick
/**
* 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);
}
}
示例8: start
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);
}
示例9: timeout
public function timeout($timeout = null)
{
if ($timeout !== null) {
$this->lastTimeout = $timeout;
}
event_add($this->ev, $this->lastTimeout);
}
示例10: sleep
private function sleep($sec = null)
{
if ($sec !== null) {
$this->lastSleepSec = $sec;
}
event_add($this->ev, $this->lastSleepSec * 1000 * 1000);
}
示例11: start
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();
}
示例12: start
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);
}
示例13: onAcceptEvent
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);
}
示例14: connectTo
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;
}
示例15: addWriteStream
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;
}