00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00016 final class SocketOutputStream extends OutputStream
00017 {
00027 const WRITE_ATTEMPTS = 15;
00028
00029 private $socket = null;
00030
00031 public function __construct(Socket $socket)
00032 {
00033 $this->socket = $socket;
00034 }
00035
00039 public function write($buffer)
00040 {
00041 if ($buffer === null)
00042 return $this;
00043
00044 $totalBytes = strlen($buffer);
00045
00046 try {
00047 $writtenBytes = $this->socket->write($buffer);
00048
00049 if ($writtenBytes === false)
00050 throw new IOTimedOutException(
00051 'writing to socket timed out'
00052 );
00053
00054 $i = 0;
00055
00056 while (
00057 $writtenBytes < $totalBytes
00058 && ($i < self::WRITE_ATTEMPTS)
00059 ) {
00060
00061 usleep(100000);
00062
00063 $remainingBuffer = substr($buffer, $writtenBytes);
00064
00065
00066 $writtenBytes += $this->socket->write($remainingBuffer);
00067
00068 ++$i;
00069 }
00070 } catch (NetworkException $e) {
00071 throw new IOException($e->getMessage());
00072 }
00073
00074 if ($writtenBytes < $totalBytes)
00075 throw new IOException(
00076 'connection is too slow or buffer is too large?'
00077 );
00078
00079 return $this;
00080 }
00081 }
00082 ?>