-1

I'm working on a chat system using Ratchet websockets. It's necessary to start the server from the terminal command "php " but I need to let this happen automatically when a user opens the chat page. I tried exec(), shell_exec() and system() but the problem is that my chat-server.php file does not return a message, it just starts the server causing the localhost to keep loading. Here's the chat-server.php file:

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    8080
);
$server->run();

And here's my messages controller that loads the view:

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');

    class Messages extends CI_Controller {  

    function index()
    {
        $this->load->view( 'includes' );
        $this->load->view( 'messages_view' );
    }
}
user3054529
  • 39
  • 1
  • 7

1 Answers1

1

That is because PHP waits until the exec(), shell_exec() and system() command finishes. You must change the way you call exec to make it start a separate process. The solution can be found here most simple way to start a new process/thread in PHP

Community
  • 1
  • 1
lorenzobe
  • 74
  • 7
  • That's awesome it works now !! one more question if you don't mind, how can I kill that process once the user closes the chat page ? – user3054529 Mar 09 '16 at 17:38
  • @user3054529 the short answer: You don't. http://stackoverflow.com/a/11026165/4854216 – Ghedipunk Mar 09 '16 at 22:09
  • @user3054529 I haven't used Ratched but maybe you can detect activity on the websocket? Like users leaving or an inactive chat and based on that close the socket so the php process ends itself? – lorenzobe Mar 10 '16 at 09:39