note 69229 added to function.stream-get-contents

From: Date: Mon, 28 Aug 2006 08:04:52 +0000
Subject: note 69229 added to function.stream-get-contents
Groups: php.notes 
Request: Send a blank email to php-notes+get-116413@lists.php.net to get a copy of this message
Per wez (at php.net), "the trick is to tell the recipient how big the packet is, so that it can read the correct length." In my own experience, when using PHP streams to send data bursts, the "max length" parameter seems to act more as an exact length parameter, as the stream will block indefinitely until max length is reached or until the other side fcloses() the stream. The latter is ok unless you need to keep the stream open to continue communication, in which case you have to let the receiving end know how much data to expect, or it will block indefinitely if the max length of data is not sent. You need to pack() and prepend the length of the outgoing data stream in the first 4 bytes of the packet, as follows: function send_pkt($stream, $my_data) { $len = strlen($my_data); $send_data = pack('N', $len) . $my_data; //Pack the length in a network-friendly way, then prepend it to the data. $final_len = strlen($send_data); if ( fwrite($stream, $send_data) < $final_len ) { //something went wrong, trigger error } } function recv_pkt($stream) { $packed_len = stream_get_contents($stream, 4); //The first 4 bytes contain our N-packed length $hdr = unpack('Nlen', $packed_len); $len = $hdr['len']; $recvd_data = stream_get_contents($stream, $len); return $recvd_data; } ---- Server IP: 64.71.164.2 Probable Submitter: 69.141.49.183 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.stream-get-contents.php Edit -- https://master.php.net/note/edit/69229 Del: integrated -- https://master.php.net/note/delete/69229/integrated Del: useless -- https://master.php.net/note/delete/69229/useless Del: bad code -- https://master.php.net/note/delete/69229/bad+code Del: spam -- https://master.php.net/note/delete/69229/spam Del: non-english -- https://master.php.net/note/delete/69229/non-english Del: in docs -- https://master.php.net/note/delete/69229/in+docs Del: other reasons-- https://master.php.net/note/delete/69229 Reject -- https://master.php.net/note/reject/69229 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#116413) next »