Mcloide's resources library

All about PHP, Javascript, concepts and development

Zend Exam Tips – Streamming

Posted by mcloide on September 2, 2008

I will not only talk about the streamming question that I got on this latest Mock Exam, but as well something that I have noticed. The first time that I did this exam I went well, so the next exam wasn’t so hard and I went very well. This time that I took the exam, it was way harder than before and very close to what I got in the real Zend Certification Exam that I took last year, so as a tip, you should consider scoring Excellent in all topics of the Mock Exam so you can always get the most of the questions in the Mock Exam.

Now about the streamming, take a look at this question. It’s an essay type of question and it’s really not so hard, but it will get you confused.

 

Consider the following PHP script:

 

<?php

function get_socket($host, $port) {

  $fr = fsockopen($host, $port);

  stream_set_blocking($fr, false);

  return $fr;

}

 

// Assume $host1, $host2, etc are defined properly

$write_map[] = array(‘fr’ => get_socket($host1, $port1),

                     ‘data’ => str_pad(“”, 500000, “A”));

$write_map[] = array(‘fr’ => get_socket($host2, $port2),

                     ‘data’ => str_pad(“”, 500000, “B”));

$write_map[] = array(‘fr’ => get_socket($host3, $port3),

                     ‘data’ => str_pad(“”, 500000, “C”));

 

do {

  $write_sockets = array();

 

  foreach($write_map as $data) {

    $write_sockets[] = $data['fr'];

  }

 

  $num_returned = stream_select($r = null, $write_sockets, $e = null, 30);

 

  if($num_returned) {

    foreach($write_sockets as $fr) {

      foreach($write_map as $index => $data) {

        if($data['fr'] === $fr) {

          $len = fwrite($fr, $data['buf']);

 

          if($len) {

            $data['buf'] = substr($data['buf'], $len);

 

            if(empty($data['buf'])) {

              fclose($data['fr']);

              /* ????????? */

            }

          }

        }

      }

    }

  }

} while(count($write_map));

?>

What should go in the ??????? above for this script to function properly?

The answer for this question is simple: 

unset($write_map[$index]);

The answer by itself shows the logic that is behind the script and if you stop and read again the question you will see that this is really the only logic you can use. After the buffer has been written on the server, to avoid it continuing in an insane loop, you should unset the array in that index. Take a look at the while condition and you will understand.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>