<?php

namespace Thrift\Transport;

use Thrift\Exception\TException;
use Thrift\Factory\TStringFuncFactory;

class TSocketServer extends TTransport {
  private $address = null;
  private $client = null;
  private $server = null;
  
  
    public function __construct($address) {
        $this->address = $address;
    }
  
    public function open()
    {
        $this->server = stream_socket_server($this->address, $errno, $errorMessage);
        if ($this->server === false) {
            throw new TException("Could not bind to socket: $errorMessage");
        }
        
        $this->client = @stream_socket_accept($this->server, 3600);
        if (!$this->client){
            throw new TException("Could not accept connection");
        }
    }
    
    public function close()
    {
        fclose($this->client);
    }
    
    public function isOpen()
    {
        return !is_null($client);
    }
    
    public function read($len)
    {
        do {
            $data = @fread($this->client, $len);
        } while ($data === FALSE || $data === '');

        return $data;
    }
    
    public function write($buf)
    {
        while (TStringFuncFactory::create()->strlen($buf) > 0) {
        $got = @fwrite($this->client, $buf);
        if ($got === 0 || $got === FALSE) {
            throw new TException('TPhpStream: Could not write '.TStringFuncFactory::create()->strlen($buf).' bytes');
        }
            $buf = TStringFuncFactory::create()->substr($buf, $got);
        }
    }
    
    public function flush()
    {
        @fflush($this->client);
    }
}
