#11 2014.03.07 11:42

Gemorroj
Administrator
Откуда: Белоруссия
Зарегистрирован: 2007.11.03
Сообщений: 6593
Карма: 107
Профиль Веб-сайт

Re: Программирование сокетов в php

TLENS, а почему use не пользуешься, а пишешь неймспейсы постоянно?
P.S. код закрыт в целом?

Неактивен

#12 2014.03.08 14:26

TLENS
Moderator
Откуда: Украина
Зарегистрирован: 2009.04.05
Сообщений: 2402
Карма: 14
Профиль

Re: Программирование сокетов в php

Gemorroj написал:

а почему use не пользуешься, а пишешь неймспейсы постоянно?

Ну данный вызов класса находится в глобальной области. По этому и не юзал пространство. Да и вообще привычка не юзать прастранства. Видимо опасаюсь несовместимости.

Gemorroj написал:

код закрыт в целом?

Вообще то не планировал целый проект в публику выносить по соображениям безопасности. Но пока месть он то и не готов, только только формируется архитектура сайта. Потом может и сверкну гитхабом но только в приватном доступе.

Неактивен

#13 2014.05.21 20:55

TLENS
Moderator
Откуда: Украина
Зарегистрирован: 2009.04.05
Сообщений: 2402
Карма: 14
Профиль

Re: Программирование сокетов в php

TLENS написал:

В общем запилил себе такой класс. Удобно работать.

Код:

1
span style="color: #0000BB"><?phpnamespace Loader;require_once __DIR__ . '/_Link.php';require_once __DIR__ . '/_IP.php';/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. *//** * Description of Multi * * @author Dmitriy Bondarenko <TLENS at tlens.ru> */class Multi { //put your code here private $_timeout; private $_length = 0; /** @var array */ private $_links = array(); private $_callback = array(); private $_ch = array(); private $_chm; public function __construct($timeout = 10) { $this->_chm = curl_multi_init(); $this->_timeout = $timeout; $this->_length = 0; } public function addLink(\Loader\Link $link, $callback = null) { $this->_links[$this->_length] = $link; $this->_callback[$this->_length] = $callback; $this->_ch[$this->_length] = curl_init((string)$link); curl_setopt($this->_ch[$this->_length], CURLOPT_HEADER, false); curl_setopt($this->_ch[$this->_length], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->_ch[$this->_length], CURLOPT_TIMEOUT, $this->_timeout); if (\Loader\IP::V6 == $link->getIp()->type()) curl_setopt($this->_ch[$this->_length], CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); if ((string)$link->getIp()) curl_setopt($this->_ch[$this->_length], CURLOPT_INTERFACE, (string)$link->getIp()); switch ($link->scheme()) { case 'https': curl_setopt($this->_ch[$this->_length], CURLOPT_PORT, $link->port() ? $link->port() : '443'); curl_setopt($this->_ch[$this->_length], CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($this->_ch[$this->_length], CURLOPT_SSL_VERIFYHOST, 0); break; case 'http': curl_setopt($this->_ch[$this->_length], CURLOPT_PORT, $link->port() ? $link->port() : '80'); break; default : break; } curl_multi_add_handle($this->_chm, $this->_ch[$this->_length]); $this->_length++; } public function run () { $rh = null; do { curl_multi_exec($this->_chm, $rh); curl_multi_select($this->_chm); } while ($rh > 0); $results = array(); for ($i = 0; $i < $this->_length; $i++) { $results[$i] = $this->_links[$i]->parser( curl_multi_getcontent($this->_ch[$i]), curl_getinfo($this->_ch[$i]), curl_error($this->_ch[$i])); if (gettype($this->_callback[$i]) == 'object') $this->_callback[$i]($results[$i]); } return $results; } }?>

Внес некоторые критические обновления в класс. На другой машине метод run() ни разу не выполнился быстрее чем за 1 сек. в логах как правило ~1.001. Пришлось подправить пару строк начиная с 99ой

Код:

1
span style="color: #0000BB"><?php/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. *//** * Description of CurlMulti * * @author Dmitriy Bondarenko <TLENS at tlens.ru> */class CurlMulti { //put your code here /** @var int */ private $_timeout; private $_length = 0; /** @var array */ private $_links = array(); /** @var array */ private $_callback = array(); /** @var array */ private $_ch = array(); private $_chm; public function __construct($timeout = 10) { $this->_chm = curl_multi_init(); $this->_timeout = $timeout; $this->_length = 0; } public function addLink($link, $callback = null) { if (is_array($link)) { foreach ($link as $k=>$v) { $this->addLink($v, $callback); } return; } $this->_links[$this->_length] = $link; $this->_callback[$this->_length] = $callback; $this->_ch[$this->_length] = curl_init($link.''); curl_setopt($this->_ch[$this->_length], CURLOPT_HEADER, false); curl_setopt($this->_ch[$this->_length], CURLOPT_RETURNTRANSFER, true); curl_setopt($this->_ch[$this->_length], CURLOPT_TIMEOUT, $this->_timeout); curl_setopt($this->_ch[$this->_length], CURLOPT_ENCODING ,""); if (IP::V6 == $link->getIp()->type()) curl_setopt($this->_ch[$this->_length], CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); if ((string)$link->getIp()) curl_setopt($this->_ch[$this->_length], CURLOPT_INTERFACE, (string)$link->getIp()); switch ($link->scheme()) { case 'https': curl_setopt($this->_ch[$this->_length], CURLOPT_PORT, $link->port() ? $link->port() : '443'); curl_setopt($this->_ch[$this->_length], CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($this->_ch[$this->_length], CURLOPT_SSL_VERIFYHOST, 0); break; case 'http': curl_setopt($this->_ch[$this->_length], CURLOPT_PORT, $link->port() ? $link->port() : '80'); break; default : break; } curl_multi_add_handle($this->_chm, $this->_ch[$this->_length]); $this->_length++; } public function __destruct() { foreach($this->_ch as $i=>$ch) { curl_multi_remove_handle($this->_chm, $this->_ch[$i]); } curl_multi_close($this->_chm); } public function run () { $rh = null; /* do { curl_multi_exec($this->_chm, $rh); curl_multi_select($this->_chm); } while ($rh > 0); */ $active = null; do { $mrc = curl_multi_exec($this->_chm, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc == CURLM_OK) { if (curl_multi_select($this->_chm) != -1) { do { $mrc = curl_multi_exec($this->_chm, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } $results = array(); for ($i = 0; $i < $this->_length; $i++) { $results[$i] = curl_multi_getcontent($this->_ch[$i]); if (gettype($this->_callback[$i]) == 'object') $this->_callback[$i]( $results[$i], curl_getinfo($this->_ch[$i]), curl_error($this->_ch[$i])); } $this->clear(); return $results; } public function clear() { //... }}?>

Неактивен

#14 2014.05.21 21:26

TLENS
Moderator
Откуда: Украина
Зарегистрирован: 2009.04.05
Сообщений: 2402
Карма: 14
Профиль

Re: Программирование сокетов в php

Кстати только что допилил интересный класс для работы.
Теперь загружать данные можно просто как через file_get_contents но переданная ссылка добавляется в стек и начинает асинхронно загружаться вместе со всем стеком только тогда когда какие то данные понадобятся.
Используется он так:

Код:

1
span style="color: #0000BB"><?php$mt = microtime(true);$data = new RemoteData('http://localhost');$data2 = new RemoteData('http://www.youtube.com');$data3 = new RemoteData('http://www.google.com');echo (($mt2 = microtime(true)) - $mt) . PHP_EOL; // 0.00035echo 'length $data: '. strlen($data) . PHP_EOL; // length $data: 3015echo 'length $data2: '. strlen($data2) . PHP_EOL; // length $data2: 234054echo 'length $data3: '. strlen($data3) . PHP_EOL; // length $data3: 48216echo (($mt3 = microtime(true)) - $mt2) . PHP_EOL; // 0.57928

ну и собственно сам класс)

Код:

1
span style="color: #0000BB"><?php/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. *//** * Description of RemoteData * * @author Dmitriy Bondarenko <TLENS at tlens.ru> */class RemoteData { static protected $_stack; static protected function load() { if (!(sizeof(self::$_stack) > 0)) return 0; $counter = 0; $loader = new CurlMulti(); foreach (self::$_stack as $k=>&$handle) { $loader->addLink($handle->_link, function ($data, $info, $error) use (&$handle) { $handle->_data = $data; $handle->_info = $info; $handle->_error = $error; }); $counter++; unset(self::$_stack[$k]); } $loader->run(); return $counter; } protected $_link = null; protected $_data = null; protected $_info = null; protected $_error = null; public function __construct($url, $eth = null) { $this->_link = new Link($url, $eth); self::$_stack[] = $this; } public function getData() { if (!$this->init()) return null; return $this->_data; } public function getInfo() { if (!$this->init()) return null; return $this->_info; } public function getError() { if (!$this->init()) return null; return $this->_error; } private function init() { return !($this->_info === null && self::load() < 1); } public function __toString() { return (string)$this->getData(); } }?>

Неактивен

#15 2014.05.22 12:48

Gemorroj
Administrator
Откуда: Белоруссия
Зарегистрирован: 2007.11.03
Сообщений: 6593
Карма: 107
Профиль Веб-сайт

Re: Программирование сокетов в php

а класс Link где?
мне кажется архитектура была бы более правильной если бы использование выглядело как-то так:

Код:

1
span style="color: #0000BB"><?php$processor = new RemoteData();$processor->add('http://example.com');$processor->add('http://wapinet.ru');$processor->load();

Неактивен

#16 2014.05.22 15:08

TLENS
Moderator
Откуда: Украина
Зарегистрирован: 2009.04.05
Сообщений: 2402
Карма: 14
Профиль

Re: Программирование сокетов в php

Ну собственно архитектура так и выглядит в классе CurlMulti.
А здесь используется агрегирование т.е. RemotData создан для упрощенного использования класса CurlMulti

Код:

1
span style="color: #0000BB"><?php/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. *//** * Description of _Link * * @author Dmitriy Bondarenko <TLENS at tlens.ru> */class Link { /** @var string */ private $_url; /** @var IP */ private $_bind; /** @var string */ private $_scheme; /** @var int */ private $_port; public function __construct($url, IP $bind = null) { $this->_url = $url; if (!$bind) $this->_bind = new IP(); else $this->_bind = $bind; $purl = parse_url($url); $this->_scheme = @$purl['scheme']; $this->_port = @$purl['port']; } public function __toString() { return $this->_url; } /** @return IP */ public function getIp() { return $this->_bind; } public function scheme() { return $this->_scheme; } public function port() { return $this->_port; }}?>

Код:

1
span style="color: #0000BB"><?php/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. *//** * Description of IP * * @author Dmitriy Bondarenko <TLENS at tlens.ru> */class IP { const V6 = 6; const V4 = 4; private $_type; private $_ip; public function __construct($ip = null) { switch ($ip) { case static::V6: case static::V4: $this->_type = $ip; $this->_ip = static::randIp($ip); break; default : if (false !== strpos($ip, ':')) { if ($ip = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $this->_type = static::V6; $this->_ip = $ip; break; } } elseif (false !== strpos($ip, '.')) { if ($ip = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { $this->_type = static::V4; $this->_ip = $ip; break; } } case null: $this->_type = static::V4; $this->_ip = static::randIp(static::V4); break; } } static private function randIp($type) { return ''; } public function type() { return $this->_type; } public function ip() { return $this->_ip; } public function __toString() { return $this->ip(); }}?>

И да слово "правильная" архитектура относительное.
Как тебе вообще такая архитектура?

Код:

1
span style="color: #0000BB"><?phpclass Videos implements ArrayAccess { // ... public function moduleGet($keyMod) { if ($this->moduleExists($keyMod)) return $this->_Modules[$keyMod]; else throw new Exception("Cannot module \"$keyMod\""); } //--------------------------- MAGIC METHODS ------------------------------// public function __get($keyMod) { return $this->getModuleKey($keyMod); } public function offsetGet($keyMod) { return $this->moduleGet($keyMod); } public function offsetExists($keyMod) { return $this->moduleExists($keyMod); } public function offsetUnset($keyMod) { throw new Exception('Cannot "Unset" to this object'); } public function offsetSet($offset, $value) { throw new Exception('Cannot be "Set" to this object'); } public function moduleExists ($keyMod) { return isset($this->_Modules[$keyMod]); } }

Можно еще имплементировать от итераторов почему бы и нет. Но мне как то не по приколу этим страдать. Но рахитектура получается довольно таки гибкой и интересной.

Неактивен

#17 2014.05.26 04:13

TLENS
Moderator
Откуда: Украина
Зарегистрирован: 2009.04.05
Сообщений: 2402
Карма: 14
Профиль

Re: Программирование сокетов в php

Какая то каша получилась у меня. В ходе работы оказалось что он не совсем то и универсальный. В общем переписал все. Закрыл конструктор сделал класс синглтоном. И теперь курлмульти принимает не url а курловские дескрипторы (Разумеется добавил метод  addUrl для дефолтной загрузки) так же отказался от Link и Ip. Еще добавил полезную штуку что бы функция добавления дескриптора возвращала ссылку на ячейку стека куда запишется результат каллбека типо:
$result =& CurlMulti::getInstance()->addUrl('http://example.com', $callback, $callbackError);
В ходе работы с ним заточу данный класс и может на гитхаб закину если будет время.

Неактивен

#18 2014.05.26 21:43

TLENS
Moderator
Откуда: Украина
Зарегистрирован: 2009.04.05
Сообщений: 2402
Карма: 14
Профиль

Re: Программирование сокетов в php

И опять столкнулся с проблемой. Нельзя добавлять линки на загрузку из каллбека))

Неактивен

#19 2014.05.26 23:32

Gemorroj
Administrator
Откуда: Белоруссия
Зарегистрирован: 2007.11.03
Сообщений: 6593
Карма: 107
Профиль Веб-сайт

Re: Программирование сокетов в php

подробнее?

Неактивен

#20 2014.05.27 15:27

TLENS
Moderator
Откуда: Украина
Зарегистрирован: 2009.04.05
Сообщений: 2402
Карма: 14
Профиль

Re: Программирование сокетов в php

Да это проблема в архитектуре стек нужно переделать Просто у меня метод exec после исполнение всех callback функций закрывает все дескрипторы и очищает стеки. И если из каллбека я добавлю в стек какой то дескриптор. То мой мусорщик подумает что он уже загружен и тут же закроет и удалит его. Вместо переделывание класса из-за лени сделал костыль и обошелся без добавления ссылок на загрузку из каллбека. (Пишу что то вроде поискового паука те собираю данные с разных ресурсов)

Неактивен

Дополнительно

forum.wapinet.ru

PunBB Mod v0.6.2
0.015 s