Search code examples
phpxampppubnub

Adding PubNub to Chat Server


I wish to add PubNub to my chat server to allow for real time sending and receiving of messages. At present, the server is built in PHP as a series of switch-case actions.

However, simply adding the instantiate and subscription to the top of the server:

$pubnub = new Pubnub(
    "key",  ## PUBLISH_KEY
    "key"  ## SUBSCRIBE_KEY
);

// Subscribing to the main server channel

$pubnub->subscribe('MAIN_SERVER', function($message) {
    //var_dump($message);  ## Print Message
    return true;         ## Keep listening (return false to stop)
});

....

switch($action) 
{

    // Complete:
    case "userLogin": 
        //error_log($username,0,"error.log");
        if ($userId = authenticateUser($db, $username, $password, $gcmregid)) 
        {   
            // Then they are a user, so yes, then in app, will call the "syncWithServer" action case
            $out = json_encode(array('response' => SUCCESSFUL));

        }
        else
....

causes the server to timeout:

PHP Fatal error:  Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\Server\lib\Pubnub\Clients\DefaultClient.php on line 30

How can PubNub be integrated into my present server?


Solution

  • PHP Subscribe Loop with PubNub

    This is a blocking call. You need to run this method outside of a web-server environment. Instead you need to run your script in a command line. Also you will want to monitor this process using upstart or similar system level

    ## Process Messages
    function receive_and_process($message) {
        switch($messge->action) { ... }
    }
    
    ## This is BLOCKING
    $pubnub->subscribe('MAIN_SERVER', function($message) {
        receive_and_process($message);
        return true;
    });
    

    Your Start command would be php my-php-server.php.