如何使用php获取服务器发送事件的直播流数据?

3

你好,我正在尝试使用php进行服务器发送事件(SSE),我有一个https网址,可以获取实时流数据。以下是我的脚本,我正在尝试在无限循环中使用。

PHP:

    <?php             
        while(1)
        {  
            $get_stream_data = fopen('https://api.xyz.com:8100/update-stream/connect', 'r');

            if($get_stream_data)
            {  
                $stream_data      =  stream_get_contents($get_stream_data);            
                $save_stream_data =  getStreamingData($stream_data);

                if($save_stream_data == true)
                {               
                    continue;                
                }            
            } 
          else
            {              
                sleep(1);
                continue;            
            }
        }    

        function getStreamingData($stream_data)
        {     

            $to       = "accd@xyz.com";
            $subject  = "Stream Details"; 
            $msg      = "Stream Details : ".$stream_data; 
            $headers  = "From:streamdetail@xyz.com";        
            $mailsent = mail($to,$subject,$msg,$headers); 

            if($mailsent){
                 return true;
            }else {
                return false;
            } 
        }
    ?>

错误:
Warning: fopen(https://api.xyz.com:8100/update-stream/connect): failed to open stream: Connection timed out in /home/public_html/get_stream_data/index.php on line 4   

服务器实时更新数据,但我无法通过我的端口获取数据。

我使用以下命令在命令提示符中检查了实时流媒体。

CURL

  curl --get 'https://api.xyz.com:8100/update-stream/connect' --verbose
1个回答

1
首先,最好使用PHP的curl函数来完成。请参阅 PHP file_get_contents() 返回“无法打开流:HTTP请求失败!”的各种答案。
如果您坚持使用fopen(),那么您可能需要为SSL设置上下文,并且可能涉及安装一些证书。请参见file_get_contents(): SSL操作失败,代码为1. 更多信息(并注意有关已接受答案的安全警告)
最后,您的while(1)循环围绕在fopen()之外(对于相对罕见的故障重新启动而言还可以),但实际上您希望它在内部。这是您的代码,只需进行最小更改即可显示:
<?php
    while(1)
    {  
        $get_stream_data = fopen('https://api.xyz.com:8100/update-stream/connect', 'r');

        if($get_stream_data)while(1)
        {  
            $stream_data      =  stream_get_contents($get_stream_data);            
            $save_stream_data =  getStreamingData($stream_data);

            if($save_stream_data == true)
            {               
                continue;                
            }
            sleep(1);
        } 
      else
        {              
            sleep(1);
            continue;            
        }
    }  
更新: 上述代码仍然让我感到困扰:我认为你希望我使用fread()而不是stream_get_contents(),并且使用阻塞而不是sleep(1)(在内部循环中)。 顺便说一句,我建议将外部循环的sleep(1)更改为sleep(3)sleep(5),这是Chrome / Firefox等浏览器的典型默认值。(实际上,你应该寻找SSE服务器发送“重试”头,并将其数字用作休眠时间。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接