Re: Sockets (reading)
| From: | Jim Lucas | Date: | Wed, 26 Aug 2009 15:40:46 +0000 |
| Subject: | Re: Sockets (reading) | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-297287@lists.php.net to get a copy of this message | ||
Philip Thompson wrote:
> Hi.
>
> During a socket read, why would all the requested number of bytes not
> get sent? For example, I request 1000 bytes:
>
> <?php
> $data = @socket_read ($socket, 2048, PHP_BINARY_READ);
> ?>
>
> This is actually in a loop, so I can get all the data if split up. So,
> for example, here's how the data split up in 3 iterations (for 1000 bytes):
>
> 650 bytes
> 200 bytes
> 150 bytes
>
> But if I can accept up to 2048 bytes per socket read, why would it not
> pull all 1000 bytes initially in 1 step? Any thoughts on this would be
> greatly appreciated!
>
> Thanks,
> ~Philip
>
Is it possible that you are receiving a \r, \n, or \0 and that is
stopping the input?
Check the Parameters the second argument for Length options.
http://us3.php.net/socket_read
Here is a shortened version of a script that I use to do something similar.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
// Set time limit to indefinite execution
set_time_limit(0);
// Set the ip and port we will listen on
define('LISTEN_IP', '<your IP address>'); // IP to listin on
define('LISTEN_PORT', <port>); // Port number
define('PACKET_SIZE', 512); // 512 bytes
define('SOCKET_TIMOUT', 2); // Seconds
/* Open a server socket to port 1234 on localhost */
if ( $socket = @stream_socket_server('udp://'.LISTEN_IP.':'.LISTEN_PORT,
$errno, $errstr, STREAM_SERVER_BIND) ) {
while ( true ) {
$buff = stream_socket_recvfrom($socket, PACKET_SIZE, 0, $remote_ip);
if ( !empty($buff) ) {
print('Received Data: '.PHP_EOL);
print('Do something with it...'.PHP_EOL);
} else {
print('Empty String'.PHP_EOL);
}
}
fclose($socket);
} else {
print("[{$errno}] {$error}".PHP_EOL);
}
?>