N
N
nepster-web2014-12-31 06:43:40
PHP
nepster-web, 2014-12-31 06:43:40

SSE php and javascript

I am working with the EventSource library.
It is necessary to update the data on the page in realtime.
Customer:

<script type="text/javascript">
                    var es = new EventSource("/games/game/updateProposal/?id=<?=$proposal->proposal_id?>");
  
                    var open = function (event) 
                    {
                        console.log('Открытие');
                        
                        
                    }; 
                    
                    var listener = function (event) 
                    {
                        console.log('OK');
                        
                        //event.data = JSON.parse(event.data);
                        
                        console.log(event.data);
                    };  
                        
                      
                    
                    var error = function (event) 
                    {
                        console.log('Ошибка');
                    }; 
                
                    
                    es.addEventListener("open", open);
                    es.addEventListener("message", listener);
                    es.addEventListener("error", error);
                </script>

Server:
{   
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
        
        
        $lastEventId = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
        if ($lastEventId == 0) 
        {
            $lastEventId = (isset($_GET["key"])) ? (string)$_GET["key"] : 0;
        }
        
        $w = array(
            
            array('test1'=>1),
            array('test2'=>2),
            array('test3'=>3),
        
        );
        
        $data = ProcessingData::load()->getJson($w);
        
        
        echo "id: {$lastEventId}" . PHP_EOL;
        echo "data: $data" . PHP_EOL;
        echo PHP_EOL;
        
        
        sleep(5);
        
        ob_flush();
        flush();
        
    }

Several questions arose:
1) The server responds with 3 lines
1) id of the last event
2) data
3) empty string
I tried to remove the empty string (echo PHP_EOL;) and we no longer get into the listener.
What is this empty line for and why can't it be removed?
2) If we remove (echo PHP_EOL;) we get into the start and error event, if everything goes well in all 3 events. Why are we hitting the error event anyway?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
avalak, 2014-12-31
@avalak

1. An empty string is part of the protocol.
2. error also occurs when the connection is closed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question