/** * Service * * @return void */ public function service() { if (!$this->socket->isConnected()) { return false; } $base = new \EventBase(); $listener = new \EventListener($base, function ($listener, $fd, $address, $base) { $event = new \EventBufferEvent($base, $fd, \EventBufferEvent::OPT_CLOSE_ON_FREE); $event->setCallbacks(function ($event) { $this->protocol->handleData(new EventSocket($event)); }, function ($event) { if (0 === $event->output->length) { $event->free(); } }, function ($event, $events) { if ($events & (\EventBufferEvent::EOF | \EventBufferEvent::ERROR)) { $event->free(); } }, null); $event->enable(\Event::READ); }, $base, \EventListener::OPT_CLOSE_ON_FREE | \EventListener::OPT_REUSEABLE, -1, $this->socket->getHandle()); $base->dispatch(); }
/** * Close write stream * @return this */ public function closeWrite() { if ($this->bevWrite) { if (isset($this->bevWrite)) { $this->bevWrite->free(); } $this->bevWrite = null; } if ($this->fdWrite) { fclose($this->fdWrite); $this->fdWrite = null; } return $this; }
/** * callback_accept * * @param mixed $listener * @param mixed $fd * @param mixed $address * @access public * @return void */ public function callback_accept($listener, $fd, $address) { list($client_ip, $port) = $address; $max_conns = $this->__max_connections; $current_conns = count($this->__buffer_event); if ($current_conns >= $max_conns) { $this->log("reach max_connections {$max_conns}, client ip: {$client_ip}, disconnect client", LOG_INFO); // 断开连接 $bev = new \EventBufferEvent($this->__event_base, $fd, \EventBufferEvent::OPT_CLOSE_ON_FREE); $bev->free(); unset($bev); return; } $current_conns++; $this->__bev_key = $this->__bev_key + 1; $bev = new \EventBufferEvent($this->__event_base, $fd, \EventBufferEvent::OPT_CLOSE_ON_FREE); $bev->setCallbacks(array($this, 'callback_buffer_read'), NULL, array($this, 'callback_buffer_event'), $this->__bev_key); $bev->setTimeouts($this->__read_timeout, $this->__write_timeout); $is_enable = $bev->enable(\Event::READ); if (!$is_enable) { $log = "can not enable EventBufferEvent, client: {$client_ip}:{$port}, current connections: {$current_conns}"; $this->log($log, LOG_INFO); return; } $this->__buffer_event[$this->__bev_key] = array($bev, $client_ip, $port); }