Why is the message sent to the client after the loop process is complete?

I have a problem, why are messages sent to the client sent after the looping process is finished even though every process and before the process I added the function send(); to send a message to the client but the message is received by the client after the looping process is complete, here is the code

  1. how to send message to client with send(); function in realtime and no need to wait for the loop process to finish ?
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();       

 
          }          

        }
}  

Please help so I can send messages to the client server while it is looping, in the code above I use ratchet as a websocket.
Thank You