循环过程完成后为什么要发送消息给客户端?

问题描述 投票:0回答:1

我有一个问题,为什么在循环过程完成后发送给客户端的消息即使在每个过程和过程之前我都添加了函数 send();向客户端发送消息,但循环过程完成后客户端会收到消息,这是代码

public function onMessage(ConnectionInterface $from, $msg) {
        $data = json_decode($msg, true);
    
        if ($data['type'] === 'file') { 
           
        require ('../../conn.php'); 
        $fileName = $data['name'];          
        $username = $data['username']; 
        $usernameMD5 = md5($username);
        $path = $this->uploadsPath.$usernameMD5. DIRECTORY_SEPARATOR .$fileName;        
        $from->send("File '{$fileName}' uploaded and processed.");
        flush();
       
        //cek file
        if (!file_exists($path)) {
            $from->send("File '{$fileName}' not found.");
            return;
          }         
          
          //mulai proses
          $spreadsheet = IOFactory::load($path);
          $sheet = $spreadsheet->getActiveSheet();
          $total_rows = $sheet->getHighestRow() - 1;  

          
          for ($i = 2; $i <= $sheet->getHighestRow(); $i++) { 
            if ($i > $total_rows) {
                $from->send("Processed all rows.");             
                break;
            }
            $from->send("Processed row $i"); // kirim pesan ke client
            flush();       

 
          }          

        }
        }  

请帮忙,这样我就可以在循环时向客户端服务器发送消息,在上面的代码中,我使用棘轮作为 websocket。谢谢

php for-loop ratchet
1个回答
0
投票

您可以使用一种称为批处理的技术。不必在每次处理一行时都向客户端发送消息,您可以将消息累积在缓冲区中,并定期或在缓冲区达到一定大小时批量发送它们。

public function onMessage(ConnectionInterface $from, $msg) {
    $data = json_decode($msg, true);

    if ($data['type'] === 'file') { 

        require ('../../conn.php'); 
        $fileName = $data['name'];          
        $username = $data['username']; 
        $usernameMD5 = md5($username);
        $path = $this->uploadsPath.$usernameMD5. DIRECTORY_SEPARATOR .$fileName;        
        $from->send("File '{$fileName}' uploaded and processed.");
        flush();

        //cek file
        if (!file_exists($path)) {
            $from->send("File '{$fileName}' not found.");
            return;
        }         

        //mulai proses
        $spreadsheet = IOFactory::load($path);
        $sheet = $spreadsheet->getActiveSheet();
        $total_rows = $sheet->getHighestRow() - 1;

        $batchSize = 10;
        $messageBuffer = '';
        for ($i = 2; $i <= $sheet->getHighestRow(); $i++) { 
            if ($i > $total_rows) {
                $messageBuffer .= "Processed all rows.";
                break;
            }
            $messageBuffer .= "Processed row $i\n";
            if ($i % $batchSize === 0) {
                $from->send($messageBuffer);
                $messageBuffer = '';
            }
        }

        //Send any remaining messages in the buffer
        if (!empty($messageBuffer)) {
            $from->send($messageBuffer);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.