The question arose, I do not know how to correctly explain ... In short, I decided to make a simple online service to which they would connect from the phone via a socket. So, how to organize a script that will not break the connection, but will communicate with the client?

    3 answers 3

    You need a demon (service, call it what you want). It is implemented, as a rule, as a separate application, and not under the control of a web server (apache and others like it), because each new connection will spawn a thread / process that will process the request from the client and this will not be controlled by you ( unless of course you have something asynchronous). Therefore, what is offered @ Fuzzz3r does not suit you.

    On what to implement the daemon, you decide, the benefit of the funds is enough from scripting languages ​​(by the way, if PHP is closer to you, then you can write a server under PHP-CLI on it, or you might like PHPDaemon, node.js, Erlang ...) before C / C ++ and assembler (although I probably bent here :)).

    • @ Sh4dow, yes, you are right, I have not tried your approach to managing php-demons, but then I have my own reasons. I'm used to storing the configuration in files (serialized arrays that are already being corrected through the web muzzle, it also kills the daemon so that it restarts with the new settings). Yes, and the script that watches the daemon and restarts it in the event of a crash inspires more trust than I will be near the computer and restart it. In general, all these are different approaches, sometimes even holivary :). - GLAGOLA 4:34 pm
    • With regard to memory leaks, with your approach, the threat is quite real when large amounts of data are sent / sent to the daemon. - GLAGOLA 4:42 pm
    • <pre> $ request = ''; $ r1 = "; do {$ request. = $ r1; $ r1 = socket_read ($ sock, 256); } while ((strlen ($ r1)> 0) && (strlen ($ request) <REQUEST_LIMIT)); </ pre> And so on. I am not saying that your option does not work. Your version requires a lot of knowledge outside of php + not cross-platform (the transfer will not take 5 minutes) + actually the keeper is written to php for 10 minutes. And yes, I'm a fortornik ^ _ ^ - Sh4dow 4:56 pm
    • As a server platform, linux no longer appeals to me, so at the moment I don’t think about cross-platform. Keeper writing in php is a matter of taste). Regarding your cycle - unfortunately it is only suitable for text data, although it will even have problems with Unicode because of strlen (use mb_strlen :), all the same, the transmitted data can be any including Unicode characters. Unfortunately in php it is inconvenient to work with binary protocols, although this is fixed by small add-ons over pack and unpack (well, or writing your own extension for php). - GLAGOLA 5:17 pm
    • one
      Another evil joke with binary data can play the parameter mbstring.func_overload - Ilya Pirogov

    Look toward the functions socket_listen, socket_accept. Quietly working on php running Apache, by the way. Just do not port your server on port 80.

    In general, the case looks like this:

     set_time_limit(0); ini_set('max_execution_time', 0); error_reporting(0); $clients = array(); $server = /* создание сокета: create, bind, listen */; $exit = false; while (true) { if ($exit) break; // при какой-то команде полезно этот флажок менять, иначе довольно трудно вырубить. полезно еще делать if is_file('close.txt') break; для "аварийного" выключения if ($client = @socket_accept($server)) { /* новый клиент. читаем входные данные, шлем ответ, добавляем при надобности клиента в список */ } foreach ($clients as $client) { /* читаем команду, отвечаем */ } sleep(1); // дабы не перегружать сервер } foreach ($clients as $client) @socket_close($client); @socket_close($server); 
    • it works, it works, only here the picture will be interesting :) every request to the site on which this script hangs will try to launch a new server. But if you run this script from the console (php-cli) - it will fully work as a server. By the way, it will not have to be completely changed (except for the first two lines). In addition, there is not only a limitation on the running time of the php script, which you turned off, but also during the processing of the request by the Apache thread. - GLAGOLA
    • one
      Yes, you shoot a sparrow tank. Keep the Apache for the sake of one script, the server for the server. While php -f server.php will launch your script as a separate process. - GLAGOLA
    • Um, quite a crutch approach to solving a problem. Yes, it’s convenient from afar (not from the working computer) to raise the server if it fell (the only plus, I don’t see any others), but the simplest script on the bash in the loop will restart your demons without any problems. In addition, you need to remove the limit on the amount of memory occupied by the script, because a known fact - php flows. I have been looking at it for a long time :))) Apache manages the communication channel with the client and the thread / process that launched the php interpreter and set it on your script. So he will have enough strength to kill this stream :) - GLAGOLA
    • Well ... for example, the server with asya was quite calm for himself without anomalies for a month. The server with the recording of the flow of the search is a week. Just for the longer I did not put them. So I can only say that you did not try to do that. And the presence of a POST-form daemon with 15+ settings outweighs many minuses) In the end, the VPS is your server and all memory limits / timeouts and so on. Problems with memory, too, was not particularly observed. In general, it works, it is not buggy with direct hands, and this is convenient. And so - try, refute, a few working projects will not spoil your tests =) - Sh4dow
    • > sleep(1); // дабы не перегружать сервер sleep(1); // дабы не перегружать сервер Not to overload the server is, of course, good, but do you understand that your daemon will process a maximum of 1 request per second ? I advise you to read about [blocking mode] [1] and [stream_select ()] [2]> error_reporting(0); So you can not do. Never. And then, I agree with @GLAGOLA. Running a daemon through apache is nonsense. [1]: php.net/stream-set-blocking [2]: php.net/stream-select - Ilya Pirogov

    There is one problem, in php.ini (the file with php settings) there is a max_execution_time value, which imposes a limit on the execution time of the default script ~ 30, like ... And this means that it will break the connection ... In your case, you need to do either without a continuous connection, or without php (replace with something more suitable).

    • And set_time_limit (0) will not fix it? - JGDger pm
    • Will fix if hosting allows you to change it. Those. you either run it from the local machine, or with VDS / VPS / negotiate with the hoster. - Sh4dow pm
    • It's not a problem. Moreover, php demons run through php_cli, which has no time limit by default. - Ilya Pirogov