libkdegames/kggznet
kggzpacket.cpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include "kggzpacket.h"
00022
00023 #include <kdebug.h>
00024
00025 #include <qabstractsocket.h>
00026
00027 KGGZPacket::KGGZPacket()
00028 {
00029 m_socket = NULL;
00030
00031 m_inputstream = new QDataStream(&m_input, QIODevice::ReadOnly);
00032 m_outputstream = new QDataStream(&m_output, QIODevice::WriteOnly);
00033 }
00034
00035 KGGZPacket::~KGGZPacket()
00036 {
00037 if(m_socket)
00038 {
00039 flush();
00040 delete m_socket;
00041 }
00042 }
00043
00044 QDataStream *KGGZPacket::inputstream()
00045 {
00046 return m_inputstream;
00047 }
00048
00049 QDataStream *KGGZPacket::outputstream()
00050 {
00051 return m_outputstream;
00052 }
00053
00054 void KGGZPacket::flush()
00055 {
00056 QByteArray packsize;
00057 QDataStream packsizestream(&packsize, QIODevice::WriteOnly);
00058 packsizestream << (qint16)(m_output.size() + 2);
00059
00060 kDebug(11005) << "<kggzpacket> flush; packsize =" << m_output.size();
00061
00062 m_socket->write(packsize.data(), packsize.size());
00063 m_socket->write(m_output.data(), m_output.size());
00064 m_output.truncate(0);
00065 }
00066
00067 void KGGZPacket::slotNetwork(int fd)
00068 {
00069 qint64 avail;
00070 qint64 len;
00071 QByteArray packsize;
00072 QDataStream packsizestream(&packsize, QIODevice::ReadOnly);
00073 qint16 size;
00074
00075 if(!m_socket)
00076 {
00077 kDebug(11005) << "<kggzpacket> init socket device";
00078 m_socket = new QAbstractSocket(QAbstractSocket::TcpSocket, this);
00079 m_socket->setSocketDescriptor(fd);
00080 }
00081
00082 if(m_input.size() == 0)
00083 {
00084 if(m_socket->bytesAvailable() < 2) return;
00085 packsize.resize(2);
00086 avail = m_socket->read(packsize.data(), 2);
00087 if(avail == -1)
00088 {
00089
00090 }
00091 packsizestream >> size;
00092 m_size = (int)size - 2;
00093 m_input.resize(m_size);
00094 kDebug(11005) << "<kggzpacket> input init; packsize = 2 + " << m_size;
00095 }
00096
00097 len = m_socket->bytesAvailable();
00098 if(len > m_size - m_input.size()) len = m_size - m_input.size();
00099 avail = m_socket->read(m_input.data() + m_input.size(), len);
00100 if(avail == -1)
00101 {
00102
00103 }
00104 kDebug(11005) << "<kggzpacket> input; read up to" << m_input.size();
00105
00106 if(m_input.size() == (qint64)m_size)
00107 {
00108 kDebug(11005) << "<kggzpacket> input done for packet; fire signal!";
00109 emit signalPacket();
00110 m_input.truncate(0);
00111 }
00112 }
00113
00114 #include "kggzpacket.moc"