kakserpom / phpdaemon Goto Github PK
View Code? Open in Web Editor NEWAsynchronous server-side framework for network applications implemented in PHP using libevent
Home Page: http://daemon.io/
License: GNU Lesser General Public License v3.0
Asynchronous server-side framework for network applications implemented in PHP using libevent
Home Page: http://daemon.io/
License: GNU Lesser General Public License v3.0
/etc/init.d/phpd.sh :
exec phpd start
Собственно делал так:
sudo chmod +x /etc/init.d/phpd.sh
sudo update-rc.d phpd.sh defaults 99
Все бы нормально, но демон, после загрузки системы не отвечает на команды stop. Не убивается через kill, или killall -9 phpd.
И еще страннее то, что запросы стали обрабатываться по 7-9 секунд.
В чем может быть причина?
С уважением Somebi
foreach (Daemon::$appInstances as $app) { foreach ($app as $appInstance) { if (!$appInstance->ready) { $this->ready = TRUE; $appInstance->onReady(); } }
$appInstance->ready = TRUE; Will be better :)
MongoNode.php
$this->LockClient->job(__CLASS__,TRUE,function($jobname) use ($appInstance) { $this->pushRequest(new MongoNode_ReplicationRequest($this,$this)); });
You can't use $this with closures
Когда будет релизован 13-ый протокол websocket?
Sec-WebSocket-Version:13
поэтому не получается использовать phpdaemon в новой версии хрома
подробности зесь http://blog.chromium.org/2011/08/new-websocket-protocol-secure-and.html
The file has an error in a comment.
Brace on the line number 33 should be commented out
В автозагрузчикке есть смысл дописать проверку, которая бы проверяла - является ли первая часть PHPDaemon, и если нет - не теряла её... потратил какое-то время (три вечера), прежде чем нашел причину конфликта своих классов и вашими. Удачи в разработке!
Как-то так:
if (sizeof($parts) > 1 && 'PHPDaemon' == $parts[0]) {
// namespaces support (remove first "PHPDaemon" part)
array_shift($parts);
}
Some logic problem I think.
Daemon_WorkerThread.class.php in 353
$this->setStatus(3);
And then in 360
if ($r->running) {$r->finish(-2);}
But if any Request in Queue (MongoNode_ReplicationRequest for example) then it will overwrite status at Request::onWakeup()
День добрый. Решил попробовай ваш продукт, тот который phpdaemon, как альтернативу php-fpm (как я понял, они чемто похожи по принципу работы, но пхпд - более тру :) ). Но возникло пару вопросов по этому поводу.
Пробовал поставить все кучей как по мануале на гитхабе - но с компиляцией пхп не сложилось, потом еще были разбежности (убунта 11) и пришлось по другому мануалу ставить - http://www.welinux.ru/post/4234/
Кой-как поставилось (я с линухом пока на Вы). Пути следующие:
1-й вопрос.
при запуске пхпд вылетает следующая ошибка в консоль:
[PHPD] Your application resolver '/etc/phpdaemon/AppResolver.php' is not available.
тут не пойму - нужно указать путь к AppResolver.php в /opt/phpdaemon/conf/phpd.conf или чтото другое?
2-й.
"Посмотрите раздел [Разработка приложений] для получения более детальной информации касаемо разработки приложений.."
Не нашел такого раздела на гитхабе.
3.й
Обьясните вкратце следующее. Допустим, в nginx'е при запросе к пхп-файлам происходит обращение к пхпдемону. (fastcgi_pass 127.0.0.1:9000; fastcgi_param APPNAME yourapplication;
). Точка входа (index.php) должна содержать какойто специальный код или он без изменения (например, просто echo 'hello';)?
И в какой момент происходит обращение ко всем файлам /opt/phpdaemon/application/*, да и вообще ко всем пхп-файлам в пхпдемоне?
Прочитал все те 5 статей про этот демон, некоторе дважды, но вопросы вот остались. Заранее спасибо.
PS. Вроде туда запостил :)
After findOne() call, "cursor" will not be instance of MongoClientCursor but stdClass and will NEVER be removed from $this->appInstance->cursors array.
I've replaced (MongoClient.php at 657)
if (isset($this->appInstance->cursors[$cur]) && ($this->appInstance->cursors[$cur] instanceof MongoClientCursor)) {$this->appInstance->cursors[$cur]->destroy();}
with
if (isset($this->appInstance->cursors[$cur])) { if ($this->appInstance->cursors[$cur] instanceof MongoClientCursor) { $this->appInstance->cursors[$cur]->destroy(); } else { unset($this->appInstance->cursors[$cur]); } }
Can't set more then one cookie per request
Не хватает примера с сессиями.
Не могли бы вы пожалуйста сделать простой пример использования стандартных обращений с сессии.
Так как у меня не получилось.
Выкидывает ошибку:
PHP Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /usr/local/lib/phpdaemon/lib/Request.php:382) in /usr/local/lib/phpdaemon/app-examples/MyApp.php on line 82
382 строка у нас ob_flush();
public function onWakeup() {
if (!Daemon::$compatMode) {
Daemon::$process->setStatus(2);
}
ob_flush();
$this->running = TRUE;
Daemon::$req = $this;
}
Где правильнее будет вызывать session_start() чтобы она вызывалась до отдачи заголовков?
Спасибо за замечательную реализацию. Благодаря вам смог быстро и практически безболезненно отказаться от apache2.
The project began to be used the function "ctype", please specify the documentation on the requirements for PHP.
Пытаюсь выяснить что именно обрезает или вообще не возвращает html при ajax запросах.
На стадии onFinish() экземпляра HTTPRequest html строка еще целая.
А дальше уже нет.
Что идет дальше, после onFinish?
С уважением Somebi.
Subj. phpDaemon require PHP > 5.3, so providing namespaces will a good step.
String #16, must be:
var params = {
url:{
ws : 'ws://'+document.domain+'/exampleApp',
comet : 'http://'+document.domain+'/WebSocketOverCOMET/?_route=exampleApp',
polling : 'http://'+document.domain+'/WebSocketOverCOMET/?_route=exampleApp', },root : '/websocket/js/'
};
Don't scan array with connections, to find free one, rewrite it using fifo stack of free connections
The file has an error in a comment.
The comment says "// 'mod-websocket-enable' => 1," but it should have been "// 'mod-websocketserver-enable' => 1,", or it won't work.
This caused me a lot of frustration :D.
Daemon does not include wrong path defined in config SILENTLY.
I think it should said something like "File ... does not exists..."
С появлением 5.4 ветки появилась замечательная возможность, поднимать веб-сервер средствами самого интерпретатора.
Возможно стоит ввести какую поддержку этой фичи во фреймворк?
I wrote some simple tests with rtep+memcache+mongo and face a memory leak problem after each session. Unfortunately, I still can't find source of this leaks.
A lot of frameworks and projects, has a class of Request, which can interfere with the class of phpDaemon. The conflict in that class of project simply not declared.
When I stop server there are so error in javascript console:
[WebSocket] failed to connect Web Socket server (SecurityError) make sure the server is running and Flash socket policy file is correctly placed
webSocketError(message="%5BWebSocket%5D%20faile...is%20correctly%20placed")websoc...lash.js (line 309)
message = "%5BWebSocket%5D%20faile...is%20correctly%20placed"
websocket_flash.js (line 309)
And when I start server I must press F5 on web interface.
There are no method to pass HTTP request from method HTTPRequest::run() of the one application to the another application in phpDaemon. I can't use FileReader functionality in HTTPRequest::run() of the my application. I copy some code of the FileReader in my application now.
Suggestion, to use more simple lru implementation without hit counting and array_sort, because there might be performance problem when you have a very big amount of lambda functions.
http://www.java2s.com/Code/Java/Collections-Data-Structure/LruHashtable.htm
asyncServer::closeConnection() doesn't clear poolState array.
I've added
unset($this->poolState[$connId]);
at line 304
PHP Notice: Undefined offset: 1 in /usr/local/phpdaemon/lib/Daemon_ConfigParser.class.php on line 202
PHP Notice: Undefined offset: 1 in /usr/local/phpdaemon/lib/Daemon_ConfigParser.class.php on line 197
etc
./phpd --config-file=http://10.0.0.15:8080
send some ID, recive config. Usefull for large clusters.
phpd - php-cli, means working dl(). Will help alleviate the process starts. And dynamically load only the necessary extensions.
При попытке использовать FastCGI сервер с более чем одним рабочим процессом возникает ряд ошибок вида
[PHPD] FastCGI: Couldn't bind TCP-socket '127.0.0.1:9001' (98 - Address already in use).
ОС Ubuntu x64
Используемая конфигурация:
max-workers 10;
min-workers 1;
start-workers 2;
max-requests 1m;
max-idle 0;
FastCGI {
enable 1;
listen tcp://127.0.0.1:9001;
expose 0;
}
I do so, then plan to get all collection items:
$this->db->objects->find(function($cursor) {
foreach($cursor->items as $k => $object) {
// do something....
unset($cursor->items[$k]);
}
if (!$cursor->finished) {$cursor->getMore();}
else {
// trigger my ather code there
....
$cursor->destroy();
}
});
But this does not work properly:
PHP Notice: Undefined property: stdClass::$callback in /usr/local/phpdaemon/app-clients/MongoClient.php on line 1128
PHP Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in /usr/local/phpdaemon/app-clients/MongoClient.php on line 1128
And only some part of the collection items was fetched.
Добрый день/вечер.
Ранее устанавливал phpdaemon с git репозитория. Поскольку использую релиз Fedora, решил попробывать rpm версию.
При установке заметил что конфиги "перенесены" в /etc/phpdaemon
За основу для теста взял ExampleWebSocket.php переименовав его в WebSocketWorker.php (и класс соответственно) поместил в директорию /usr/share/phpdaemon/applications
Запустив демон, пытался подключиться, но, к сожалению, безуспешно.
Вот подробно мои действия после установки (как это описано в https://github.com/kakserpom/phpdaemon/wiki/%D0%A3%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0-%28centos-%D0%B8-fedora-linux%29 )
В phpd.conf добавил:
path '/etc/phpdaemon/conf/AppResolver.php'; autoload WebSocketWorker; WebSocketServer { privileged; enable 1; listen tcp://XXX.XXX.XXX.XXX; listenport 8049; }
В результате получаю:
на стороне клиента
[WebSocket] policy file: xmlsocket://some-site.com:843 [WebSocket] connected [WebSocket] request header: GET /chat HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: XXX.XXX.XXX.XXX:8049 Origin: http://some-site.com Cookie: Sec-WebSocket-Key1: g3q9b1 (5gs 9 t 4427 4l Sec-WebSocket-Key2: Sk12 I7 F2 8 K 66; 9J$C84S [WebSocket] sent key3: ,$Ó¨?ó�G [WebSocket] closed [WebSocket] connected [WebSocket] request header: GET /chat HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: XXX.XXX.XXX.XXX:8049 Origin: http://some-site.com Cookie: Sec-WebSocket-Key1: 581 3P"I 1 4es = 1i3 &1BS Sec-WebSocket-Key2: >DT3A +H66 (421247 7D [WebSocket] sent key3: wv÷1yظò [WebSocket] closed
на стороне сервера
[root@dev conf]# phpd start (до подключения WebSocket-клиента) [PHPD] M#25596 IPCManager instantiated. [root@dev conf]# [PHPD] M#25596 WebSocketServer instantiated. [PHPD] M#25596 WebSocketServer up. (после подключения WebSocket-клиента) [root@dev conf]# PHP Fatal error: Class 'HTTPRequest' not found in /usr/share/phpdaemon/app-servers/WebSocketServer.php on line 433 [PHPD] Spawning 1 worker(s). PHP Fatal error: Class 'HTTPRequest' not found in /usr/share/phpdaemon/app-servers/WebSocketServer.php on line 433 [PHPD] Spawning 1 worker(s).
Как нужно настраивать конфиг phpdaemon-a чтобы избежать данной ошибки?
Благодарю за внимание.
Line 165 mentions "logerrors" config variable. However if I use it I get an error saying it is not valid. So the line currently serves no purpose.
bug in public function computeKey($key) {
$result = (int) $digits; // bug (int)
if ($spaces > 0) {
$result = (int) floor($result / $spaces);
when try to connect with key > then 2147483647
test:
echo (int)'7683287632687924324';
print: 2147483647
// fixed
$result = 0;
if ($spaces > 0) {
$result = (int) @floor($digits / $spaces);
It would be nice to add a timeout in LockClient::job() method.
При попытке отправить обычный 204 No Content в браузер все равно приходит ответ 200
$request->status(204);
Обработку 204 кода добавил в http://github.com/silentroach/phpdaemon/commit/4e07c46c42e30cada72e30522af865450538c9f0
Libevent version: 2.0.11-stable
php_libevent version: 0.0.4
php version: 5.3.3-1ubuntu9.5
phpd version: currently from git
When starting get an error:
[warn] Added a signal to event base 0x146baf0 with signals already added to event_base 0x134d980. Only one can have signals at a time with the epoll backend. The base with the most recently added signal or the most recent event_base_loop() call gets preference; do not rely on this behavior in future Libevent versions.
Have problems working with FASTCGI server with one worker. I'm not sure, but it seems it gets unresponsive. I found nothing in stderr or stdout output, but Nginx had this in his log:
2011/07/29 17:03:40 [error] 7703#0: *266549 upstream sent too big header while reading response header from upstream, client: client_ip, server: www.example.com, request: "GET /someurl HTTP/1.1", upstream: "fastcgi://unix:/tmp/phpdaemon.fcgi.sock:", host: "www.example.com", referrer: "some url from google search results"
2011/07/29 17:05:59 [error] 7704#0: *266185 upstream prematurely closed connection while reading response header from upstream, client: my_server_ip, server: www.example.com, request: "GET /someurl HTTP/1.1", upstream: "fastcgi://unix:/tmp/phpdaemon.fcgi.sock:", host: "www.example.com", referrer: "my website url"
I have checked your sources and chunk size is 8196 as it's intended and required by nginx proxy buffers config defaults.
I have tried to increase buffer size of nginx even up to:
proxy_buffers 8 1024k;
proxy_buffer_size 2048k;
but it didn't helped.
Then i have decided to increase workers count from one to 20 and everything is fine now.
How much RPS one worker is capable to handle when weight of document is 80kb~?
I gonna dig sources to figure out what's happening inside there when i'll have some time for it, but would like to hear from you as well.
Thanks ;)
WebSocketSession has property server['HTTP_COOKIE'] but not parsed.
PHP Warning: runkit_import(): class xxxx is an interface in /home/Projects/phpdaemon/app-servers/IPCManager.php on line 196
MySqlClient cannot handle authenticating using pre-4.1 password scheme
Old passwords can exist even on mysql 5 servers, and this is important because some Centos distributions are still enabling old passwords by default in my.cnf
To reproduce....
Create a test account on any mysql server.....
mysql> grant all on mysql.* to testing@localhost identified by OLD_PASSWORD('testing');
mysql> update user set Password = OLD_PASSWORD('testing') where User = 'testing' and Host = 'localhost';
mysql> flush privileges;
now try using MySQLClient to connect using this login...
if ($sqlclient && ($this->sql = $sqlclient->getConnection('mysql://testing:testing@localhost/mysql')))
The authentication succeeds and mysql returns some sort of confirmation packet [\x01\x00\x00\x02\xfe]
phpdaemon treats this as simply an EOF packet, and nothing more, and as a result the onConnected callback never gets fired.
One solution is to add this into the existing EOF packet routine, but it might be better to properly parse the response elsewhere
elseif ($fieldCount === 0xFE)
{
// EOF Packet
++$this->instate;
// --- NEW: If waiting for authentication reply
if (($this->cstate == 2) && ($this->buf == "\x01\x00\x00\x02\xfe"))
{
Daemon::log("Matched token\n");
$this->instate = 3;
}
if ($this->instate === 3) {
$this->onResultDone();
}
} else {
Connection pool behaviour needed:
When loading config file in Daemon_Bootstrap.class.php and it has error then application should terminate program with error_code = 6. IMHO...
if (!Daemon::loadConfig(Daemon::$config->configfile->value)) {
exit(6);
}
PS: Now, application continue working and show some config variables and return 0 when exit.
Добрый день/вечер.
Пользуясь phpdaemon-ом, обнаружил наличие MongoClient-а.
На сколько я знаю, RedisDB побыстрее будет, но клиента к нему нету (
Хотелось бы знать, будет ли написан клиент для RedisDB, и если да, то когда его можно будет ожидать?
May be use AddDefaultCharset option in HTTPRequest for text/plain or text/html?
В общем у меня тут такой вопрос по конкретной возможности рассылки сообщения другим пользователям, на самом деле с демоном начал возиться совсем не давно но ни как не могу найти информации как это сделать.
Если быть точным нужна возможность отправки сообщений как одному так и нескольким людям но не рассылать всем кто подключен… например пользователь отправляет сообщение и в нутрии его класса находится массив с перечисленными ключами сессии тех кому нужно отправить сообщение.
Пожалуйста объясни как достучаться до чужой сессии?
Which application would handle requests.
etc.
HTTP {
aplication myApp;
}
Because 80% of the getRequestRoute only one line: return "myApp";
Perhaps we should do ucfirst of the appResolver.php in conf/
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.