<?php

namespace Kicken\Chat;


abstract class 
StreamSocketClient extends StreamSocket {
    private 
$mReadBuffer '';
    private 
$mWriteBuffer '';
    const 
READ_PACKET_SIZE 4096;

    public function 
hasPendingWrites(){
        return 
strlen($this->mWriteBuffer) > 0;
    }

    public function 
nowReadable(){
        if (
$this->mResource === null){
            return;
        }

        
$data fread($this->mResourceself::READ_PACKET_SIZE);
        if (
$data === ''){
            
$this->close();
        } else {
            
$this->mReadBuffer .= $data;
        }
    }

    public function 
nowWritable(){
        if (
$this->mResource === null || $this->mWriteBuffer === ''){
            return;
        }

        
$len fwrite($this->mResource$this->mWriteBuffer);
        
$this->mWriteBuffer substr($this->mWriteBuffer$len);
    }

    public function 
writeSocket($data){
        
$this->mWriteBuffer .= $data;
        
$this->nowWritable();
    }

    public function 
readAll(){
        
$s $this->mReadBuffer;
        
$this->mReadBuffer '';

        return 
$s;
    }
}