I'm developing an iOS app that has a chat system included (using these instructions). The api runs on a LAMP server, so I used ReactPhp instead of Twisted for python as socket handler to communicate between client/server and server/client.
This is the code I'm using for the file socket.php
<?
require 'vendor/autoload.php';
$port = 1337;
$host = '127.0.0.1';
$app = function ($request, $response) {
$response->writeHead(200, array('Content-Type' => 'text/plain'));
$response->end('Hello '.time()."
");
};
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);
$http->on('request', $app);
echo 'Server running at http://'.$host.':'.$port."
";
$socket->listen($port, $host);
$loop->run();
?>
Then I just run this on the terminal:
php socket.php
The issues:
It works fine, but... if I close the terminal (or stop the process with ctrl+Z), the port stops listening. How do I get the socket to listen all the time from the moment Apache starts?
After closing the terminal (case 1), if I try running php socket.php
again, I get this message: Could not bind to tcp://127.0.0.1:1337: Address already in use - If the port is already in use, then why am I unable to access it after closing the terminal?
It seems that php thread still running. From terminal:
ps -ef | grep php
Output:
501 7286 3848 0 10:09AM ttys002 0:00.08 php socket.php
Kill thread:
kill 7286
Update for Nino: The second issue can happend using nohup
command too.
What happens is, when you close the terminal session, you kill the process, unless you run it as a daemon.
Nohup to the rescue!
From Wikipedia:
nohup is a POSIX command to ignore the HUP (hangup) signal. The HUP signal is, by convention, the way a terminal warns dependent processes of logout.
Output that would normally go to the terminal goes to a file called nohup.out if it has not already been redirected.
If on Debian-based system (i.e. Ubuntu):
sudo apt-get install nohup
If on Fedora-based system (i.e. Centos):
sudo yum install nohup
Then, run your PHP script like this: nohup php socket.php &
This will solve your problem #1, which will in turn solve #2 as well.
If the process you just launched as a daemon writes anything to stdout
, you can see that by running cat nohup.out
from the folder where you executed the aforementioned nohup php ...
command.