1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <code>
public static function pushEvent(){
header( 'Content-Type: text/event-stream' );
header( 'Cache-Control: no-cache' );
header( 'Connection: keep-alive' );
$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);
}
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);//多少毫秒內無數據,再重連
,這行會讓前端多少毫秒後再重新建立連接,這樣覺得會非常浪費資源,而且每次要輸出數據前是讀取緩存是否有發給該用戶的消息這種方式,還有沒有別的好方式?
回覆內容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <code>
public static function pushEvent(){
header( 'Content-Type: text/event-stream' );
header( 'Cache-Control: no-cache' );
header( 'Connection: keep-alive' );
$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);
}
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...
最關鍵的是下面這段:
1 2 3 4 5 | <code>ob_flush();
flush ();
sleep(3);
</code>
|
登入後複製
flush之後,不要斷開連接,而是睡眠3秒後再次進入循環,這樣就可以保持住連接,不會斷開重連。
為什麼不透過websocket去做這樣的事呢?