How do I keep a websocket server running, even after I close the SSH terminal?

10,336

Solution 1

Make a daemon.

If you are using symfony2, you can use the Process Component.

// in your server start command
$process = new Process('/usr/bin/php bin/chat-server.php');
$process->start();
sleep(1);
if ($process->isRunning()) {
    echo "Server started.\n";
} else {
    echo $process->getErrorOutput();
}

// in your server stop command
$process = new Process('ps ax | grep bin/chat-server.php');
$process->run();
$output = $process->getOutput();
$lines = preg_split('/\n/', $output);
// kill everything (there can be multiple processes if they are spawned)
$stopped = False;
foreach ($lines as $line) {
    $ar = preg_split('/\s+/', trim($line));
    if (in_array('/usr/bin/php', $ar)
        and in_array('bin/chat-server.php', $ar)) {
        $pid = (int) $ar[0];
        posix_kill($pid, SIGKILL);
        $stopped = True;
    }
}
if ($stopped) {
    echo "Server stopped.\n";
} else {
    echo "Server not found. Are you sure it's running?\n";
}

If you are using native PHP, never fear, popen is your friend!

// in your server start command
_ = popen('/usr/bin/php bin/chat-server.php', 'r');
echo "Server started.\n";

// in your server stop command
$output = array();
exec('ps ax | grep bin/chat-server.php', &$output);
$lines = preg_split('/\n/', $output);
// kill everything (there can be multiple processes if they are spawned)
$stopped = False;
foreach ($lines as $line) {
    $ar = preg_split('/\s+/', trim($line));
    if (in_array('/usr/bin/php', $ar)
        and in_array('bin/chat-server.php', $ar)) {
        $pid = (int) $ar[0];
        posix_kill($pid, SIGKILL);
        $stopped = True;
    }
}
if ($stopped) {
    echo "Server stopped.\n";
} else {
    echo "Server not found. Are you sure it's running?\n";
}

There are of course also other helpful PHP libraries for working with daemons. Googling "php daemon" will give you a lot of pointers.

Solution 2

The ratchet documentation has a deploy page. Did you checked it?

Old answer: It may be a bad idea on a prod server (this is a personal assumption), but you can use the screen command to open a terminal, launch your daemon, then press Ctrl-A, Ctrl-D, and your terminal is still alive, opened in background. To reconnect to this terminal, connect back to your server and type screen -r.

Solution 3

From the Ratchet Deployment page:

if you are running Ubuntu, fallow these steps:

  1. install supervisor like this: Installing Supervisor

  2. configure ratchet webserver as a service program like this: Supervisor Process Control | Supervisord Install & Usage

making a conf file in /etc/supervisor/conf.d/.conf and fill the conf exmple code from Ratchet Deployment page:

[program:ratchet]
command                 = bash -c "ulimit -n 10000; exec /usr/bin/php /absolute/path/to/ratchet-server-file.php)"
process_name            = Ratchet
numprocs                = 1
autostart               = true
autorestart             = true
user                    = root
stdout_logfile          = ./logs/info.log
stdout_logfile_maxbytes = 1MB
stderr_logfile          = ./logs/error.log
stderr_logfile_maxbytes = 1MB
  1. run the following comands:

    • $ supervisorctl reread
    • $ supervisorctl update
    • and finally check if your service is running: $ supervisorctl

these are all the steps that should be added in Ratched Deployment tutorial.. but this approach may not be the best..

Solution 4

This tutorial shows a really cool way of turning the WebSocket into a *nix Service to make it persist even when you close your SSH connection.

Basically you make a file /etc/init/socket.conf with the following contents

# Info
description "Runs the Web Socket"  
author      "Your Name Here"

# Events
start on startup  
stop on shutdown

# Automatically respawn
respawn  
respawn limit 20 5

# Run the script!
# Note, in this example, if your PHP script (the socket) returns
# the string "ERROR", the daemon will stop itself.
script  
    [ $(exec /usr/bin/php -f /path/to/socket.php) = 'ERROR' ] && ( stop; exit 1; )
end script  

Blog Post:
http://blog.samuelattard.com/the-tutorial-for-php-websockets-that-i-wish-had-existed/

Share:
10,336

Related videos on Youtube

Lucas
Author by

Lucas

Updated on June 04, 2022

Comments

  • Lucas
    Lucas almost 2 years

    So, I am using Ratchet with PHP, and have currently uploaded a successful websocket example to my server.

    It works after I go to SSH, and then just manually run "php bin/chat-server.php".

    What I was wondering is that, in a commercial situation, how do I keep the chat server running?

    Thanks.

  • Narendrasingh Sisodia
    Narendrasingh Sisodia almost 9 years
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.
  • MarshallOfSound
    MarshallOfSound almost 9 years
    @Uchiha answer has been updated to include the relavent content, thanks for pointing that out
  • Lucas
    Lucas almost 9 years
    Not a bad answer - could be more of a comment, but thanks nonetheless! :D
  • SlimenTN
    SlimenTN almost 7 years
    @mattexx what do you mean // in your server start command ??
  • DerpyNerd
    DerpyNerd over 5 years
    I've been trying this too here: stackoverflow.com/questions/53489734/…. Process has a default timeout of 60 seconds which you can change $process->setTimeout(3600);. Other than that, the created process isn't detached from the current terminal. so it tends to be terminated once the terminal is closed. The same applies when running this during a user's request