#include "pqtcpsocket.h"

namespace PQ {

PQTcpSocket::PQTcpSocket(QObject *parent) : QTcpSocket(parent),_msg(false)
{
    connect(&_msg,SIGNAL(revicedMSG(MSGHeader,QByteArray)),this,SIGNAL(revicedMSG(MSGHeader,QByteArray)));
    connect(&_msg,SIGNAL(hasError()),this,SLOT(msgError()));
    connect(this,SIGNAL(readyRead()),this,SLOT(readSocketData()));
}

PQTcpSocket::~PQTcpSocket()
{}

void  PQTcpSocket::msgError()
{
    this->setErrorString("message handle error!");
    emit error(QAbstractSocket::UnknownSocketError);
    this->close();
}

void PQTcpSocket::readSocketData()
{
    _msg.readMsg(this->readAll());
}


void PQTcpSocket::writeMessage(MSGHeader header, const QByteArray & byte)
{
    header.length = byte.length();
    this->write(header.buildArray());
    if(header.length > 0)
        this->write(byte);
}

}
