function eventLoop()
    {
        // Socket not connected at all?
        if($this->socket == null) {
            return;
        }

        // Server closed connection?
        if(feof($this->socket)) {
            stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
            $this->socket = null;
            return;
        }

        // See if there's data waiting?
        $byte = $this->readBytes(1, true);
        if(strlen($byte) > 0) {
            $cmd = ord($byte);

            // Read the length of packet..
            $bytes=0;
            $multiplier=1;

            do {
                $t_byte = ord($this->readBytes(1,true));
                $bytes+=($t_byte & 127)*$multiplier;
                $multiplier*=128;

                if($multiplier>128*128*128) {
                    break;
                }
            } while( ($t_byte&128) != 0);

            //
            $payload = "";
            if($bytes>0)
                $payload = $this->readBytes($bytes, false);

            switch( $cmd & 0xf0 ) {
                case 0xd0:      // PINGRESP
                    $this->debugMessage("Ping response received");
                    break;

                case 0x30:      // PUBLISH
                    $msg_qos = ( $cmd & 0x06 ) >> 1; // QoS = bits 1 & 2
                    $this->processMessage( $payload, $msg_qos );
                    break;

                case 0x40:      // PUBACK
                    $msg_qos = ( $cmd & 0x06 ) >> 1; // QoS = bits 1 & 2
                    $this->processPubAck( $payload, $msg_qos );
                    break;
            }

            $this->timeSincePingReq = time();
            $this->timeSincePingResp = time();
        }

        if( $this->timeSincePingReq < (time() - $this->keepAlive ) ) {
            $this->debugMessage("Nothing received for a while, pinging..");
            $this->sendPing();
        }


        if( $this->timeSincePingResp < (time() - ($this->keepAlive*2)) ) {
            $this->debugMessage("Not seen a package in a while, reconnecting..");
            stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
            $this->socket = null;
        }

    }