Skip to content

Instantly share code, notes, and snippets.

@jvranish
Created November 2, 2009 20:52
Show Gist options
  • Save jvranish/224455 to your computer and use it in GitHub Desktop.
Save jvranish/224455 to your computer and use it in GitHub Desktop.
class GameTcpSocket : public QTcpSocket
{
const int timeout = 2 * 1000;
GameTcpSocket(QObject* parent = 0) : QTcpSocket(parent)
{
}
template<class T> GameTcpSocket& operator<< (T data)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint32)0;
out << data;
out.device()->seek(0);
out << (quint32)(block.size() - sizeof(quint32));
write(block)
}
template<class T> GameTcpSocket& operator>> (T& data)
{
while (bytesAvailable() < (int)sizeof(quint32)) {
if (!waitForReadyRead(timeout)) {
emit error(error(), errorString());
return;
}
}
quint32 blockSize;
QDataStream in(this);
in.setVersion(QDataStream::Qt_4_0);
in >> blockSize;
while (bytesAvailable() < blockSize) {
if (!waitForReadyRead(timeout)) {
emit error(error(), errorString());
return;
}
}
in >> data;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment