#include "../structures/header.h"
using namespace network;
using namespace structures;
-tcpClient::tcpClient(quint64 buffersize,QObject *parent):QTcpSocket(parent){
+tcpClient::tcpClient(quint64 buffersize,const QString &senderName,QObject *parent):QTcpSocket(parent){
this->buffer_size=buffersize;
+ this->senderName=&senderName;
+ this->timeout_time=TIMEOUT;
connect(this,SIGNAL(connected()),SLOT(connectedSlot()));
}
-void tcpClient::connectedSlot(){
+quint64 tcpClient::timeout()const {return this->timeout_time;}
+void tcpClient::timeout(const quint64 time){this->timeout_time=time;}
+tcpClient &tcpClient::operator<<(const QString &msg){
+ if(!this->check_connection_and_wait_connected()){return (*this);}
+ header head_data(*(this->senderName),msg);
+ QByteArray head_buffer;
+ QDataStream datastream(head_buffer);
+ datastream<<head_data;
+ quint16 size=(quint16)head_buffer.size();
+ this->write((char*)&size,sizeof(quint16)/sizeof(char));
+ this->check_byte_written_and_wait_written();
+ this->write(head_buffer);
+ this->check_byte_written_and_wait_written();
+ this->write(msg.toUtf8());
+ this->check_byte_written_and_wait_written();
+ this->disconnectFromHost();
+}
+tcpClient &tcpClient::operator<<(const QFile &file){
+}
+bool tcpClient::check_byte_written_and_wait_written(){
+ if(!this->waitForBytesWritten(this->timeout_time)){
+ this->setErrorString("The data couldn't be written.");
+ emit this->error(QAbstractSocket::UnknownSocketError);
+ return false;
+ }
+ return true;
+}
+bool tcpClient::check_connection_and_wait_connected(){
+ if(this->state()!=QAbstractSocket::ConnectingState||this->state()!=QAbstractSocket::ConnectedState){
+ this->setErrorString(tr("This socket haven't connected to somewhere yet."));
+ emit this->error(QAbstractSocket::SocketAccessError);
+ return false;
+ }
+ if(!this->waitForConnected(this->timeout_time)){
+ this->setErrorString(tr("Connection time out"));
+ emit this->error(QAbstractSocket::SocketTimeoutError);
+ return false;
+ }
+ return true;
}