final public function listen()
    {

        $this->log("Listening...");

        $x = 1;
        while($x){

            $x++;
            $xml = $this->read(1024);

            if(!empty($xml)){
                if($this->onRead($xml) === false){
                    return false;
                }
            }

            if(substr($xml, 0, 8 ) == '<message'){
                $message = new \sb\XMPP\Message($xml);
                $message->client = $this;
                $this->onMessage($message);
            } elseif(substr($xml, 0, 9 ) == '<presence'){

                $presence = new \sb\XMPP\Presence($xml);
                $from = $presence->getFrom();
                $type = $presence->getType();

                if(is_array($this->buddies_online)){

                    $status = $presence->getStatus();

                    if($from && $type == 'unavailable'){
                        unset($this->buddies_online[$from]);
                        $this->log('NOTICE: '.$from.' is unavailable');
                    } elseif($from){

                        $this->buddies_online[$from] = $status;
                        $this->log('NOTICE: '.$from.' is '.$status);
                    }
                }

                if(strstr($type, 'subscribe') && $this->onSubscriptionRequest($presence)){

                    $this->sendAcceptSubscriptionRequest($from);
                    $this->log('NOTICE: Auto accepting subscription request from '.$from);
                }

                $this->onPresence($presence);
            }

            if($x % 100 == 0){

                $presence = new \sb\XMPP\Presence();
                $presence->setStatus($this->status);


                $this->sendPresence($presence);
                $x = 1;

            }

           //extra little sleep reduces CPU
           usleep(100000);
        }
    }