>  기사  >  백엔드 개발  >  javascript - h5에는 서버에서 보낸 이벤트가 있는데 PHP 측에 어떻게 작성합니까?

javascript - h5에는 서버에서 보낸 이벤트가 있는데 PHP 측에 어떻게 작성합니까?

WBOY
WBOY원래의
2016-08-10 09:07:251051검색

<code>
public static function pushEvent(){
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache'); // 建议不要缓存SSE数据
    header('Connection: keep-alive');
    //header('X-Accel-Buffering: no');//有可能用nginx的需要设置这个才能把缓冲数据刷出去

    $serverTime = time();
    $hasData = hFile::cache('pushEvent');//读缓存
    if($hasData){
        hFile::cache('pushEvent',0);//存缓存
        self::sendMsg($serverTime, 'server time: ' . date("h:i:s"),'myevent',100000);
    }else
        self::sendMsg('','','',100);//多少毫秒内无数据,再重连
}


/**
 * @param string $id Timestamp/id of this connection.
 * @param string $msg Line of text that should be transmitted.
 * @param $event string
 */
private static function sendMsg($id='', $msg='',$event='',$retry=''){
    if(!($id||$event||$msg||$retry))
        return;

    if($retry) echo "retry: $retry" .PHP_EOL;
    if($id) echo "id: $id" . PHP_EOL;
    if($event) echo "event: {$event}" . PHP_EOL;
    if($msg) echo "data: $msg" . PHP_EOL;
    echo PHP_EOL;//表示本条数据结束
    ob_flush();
    flush();
}
</code>

이렇게 작성했습니다(코드 일부 복사). 문제는 프런트 엔드가 연결을 설정할 때마다 PHP가 데이터를 한 번만 반환할 수 있다는 것입니다. 다음 데이터를 원할 경우 self::sendMsg('','','',100);//多少毫秒内无数据,再重连 이 줄을 사용하면 다시 연결되기까지 몇 밀리초가 걸릴지 프런트 엔드에 알 수 있습니다. -연결을 설정하는 것은 매우 낭비적인 일이며, 데이터를 출력하기 전에 매번 캐시를 읽어서 사용자에게 전송되는 메시지가 있는지 확인합니다.

답글 내용:

<code>
public static function pushEvent(){
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache'); // 建议不要缓存SSE数据
    header('Connection: keep-alive');
    //header('X-Accel-Buffering: no');//有可能用nginx的需要设置这个才能把缓冲数据刷出去

    $serverTime = time();
    $hasData = hFile::cache('pushEvent');//读缓存
    if($hasData){
        hFile::cache('pushEvent',0);//存缓存
        self::sendMsg($serverTime, 'server time: ' . date("h:i:s"),'myevent',100000);
    }else
        self::sendMsg('','','',100);//多少毫秒内无数据,再重连
}


/**
 * @param string $id Timestamp/id of this connection.
 * @param string $msg Line of text that should be transmitted.
 * @param $event string
 */
private static function sendMsg($id='', $msg='',$event='',$retry=''){
    if(!($id||$event||$msg||$retry))
        return;

    if($retry) echo "retry: $retry" .PHP_EOL;
    if($id) echo "id: $id" . PHP_EOL;
    if($event) echo "event: {$event}" . PHP_EOL;
    if($msg) echo "data: $msg" . PHP_EOL;
    echo PHP_EOL;//表示本条数据结束
    ob_flush();
    flush();
}
</code>

이렇게 작성했습니다(코드 일부 복사). 문제는 프런트 엔드가 연결을 설정할 때마다 PHP가 데이터를 한 번만 반환할 수 있다는 것입니다. 다음 데이터를 원할 경우 self::sendMsg('','','',100);//多少毫秒内无数据,再重连 이 줄을 사용하면 다시 연결되기까지 몇 밀리초가 걸릴지 프런트 엔드에 알 수 있습니다. -연결을 설정하는 것은 매우 낭비적인 일이며, 데이터를 출력하기 전에 매번 캐시를 읽어서 사용자에게 전송되는 메시지가 있는지 확인합니다.

제 기사를 참조하세요: https://segmentfault.com/a/11...

가장 중요한 것은 다음 단락입니다.

<code>ob_flush();
flush();
//等待3秒钟,开始下一次查询
sleep(3);
</code>

플러싱 후에는 연결을 끊지 말고 3초 동안 Sleep한 후 다시 루프에 들어가야 연결이 유지되고 끊어졌다가 다시 연결되지 않습니다.

웹소켓을 통해 이런 작업을 수행해 보는 것은 어떨까요?

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.