Search code examples
phpapacheyii2server-sent-events

Apache + SSE + PHP


I'm using SSE to send some data to browser (web chat). And I faced with some problem. SSE works fine but other requests no. All requests stays at pending status for a very long time, even click on link to another page doesnt work, untill browser stop button would be pressed. I tested it on PHP 5.4.4, 5.4.45 and Apache 2.4 and 2.2... Absolutely same result. I tried to change mpm settings in apache.conf and nothing changed. Anyone have any ideas what could help me?

This is the action from controller:

/**
 * @return string
 */
public function actionIndex()
{
    /** @var SSE $sse */
    $sse = \Yii::$app->sse;
    $sse->addEventListener('message', new MessageEventHandler());
    $sse->start();

}

And this is message handler:

class MessageEventHandler extends SSEBase
{
    public function check()
    {
        return true;
    }

    public function update()
    {
        return 'New message!';
    }
}

And browser side:

var sseObject = $.SSE('/notifier', {
    events: {
        chat_message: function (e) {
            console.log(e.data);
        }
    }
});
sseObject.start();

Solution

  • Problem is probably with session lock.

    PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing.

    Combined with fact that SSE connections are persistent, thus session will stay locked.

    http://konrness.com/php5/how-to-prevent-blocking-php-requests/

    Possible solution is to call session_write_close() in actionIndex().