1 /***************************************************************************
2 * Copyright (C) 2006 by David Cuadrado *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
23 #include <QTextStream>
26 #include <dcore/debug.h>
30 #include "socketobserver.h"
35 struct Socket::Private
37 Private() : format(Text
) {}
39 QQueue
<QByteArray
> queue
;
40 QList
<SocketObserver
*> observers
;
45 Socket::Socket(QObject
*parent
)
46 : /*QSslSocket*/QTcpSocket(parent
), d(new Private
)
48 connect(this, SIGNAL(readyRead ()), this, SLOT(readFromServer()) );
49 connect(this, SIGNAL(connected()), this, SLOT(sendQueue()));
50 connect(this, SIGNAL(disconnected()), this, SLOT(clearQueue()));
59 void Socket::setFormat(Format format
)
64 Socket::Format
Socket::format() const
69 void Socket::addObserver(SocketObserver
*observer
)
71 d
->observers
<< observer
;
74 void Socket::removeObserver(SocketObserver
*observer
)
76 d
->observers
.removeAll(observer
);
79 void Socket::sendQueue()
81 while( d
->queue
.count() > 0 )
83 if ( state() == QAbstractSocket::ConnectedState
)
85 send(d
->queue
.dequeue());
91 void Socket::clearQueue()
96 void Socket::send(const QByteArray
&data
)
98 if( state() == QAbstractSocket::ConnectedState
)
104 QTextStream
stream(this);
105 stream
<< data
.toBase64() << "%%" << endl
;
117 d
->queue
.enqueue(data
);
121 void Socket::send(const QDomDocument
&doc
)
123 send(doc
.toString(0).toLocal8Bit());
126 void Socket::readFromServer()
133 while(this->canReadLine())
135 readed
+= this->readLine();
137 if ( readed
.endsWith("%%\n") )
139 readed
.remove(readed
.lastIndexOf("%%"), 2);
144 if ( !readed
.isEmpty() )
146 readed
= QByteArray::fromBase64(readed
.toLocal8Bit());
148 foreach(SocketObserver
*o
, d
->observers
)
157 while(bytesAvailable() > 0)
159 QByteArray data
= this->read(1024);
160 foreach(SocketObserver
*o
, d
->observers
)
169 if (this->bytesAvailable() > 0) readFromServer();