M
M
Maxim Rudnev2016-07-21 15:42:37
Qt
Maxim Rudnev, 2016-07-21 15:42:37

How to use QDataStream?

Questions for connoisseurs.
1: (it's a method of adding one string to the end of another, right?) append() is used like this:

QString str = "rock and";

    str.append(" roll");            // str == "rock and roll"

In my example from the textbook, it append("Sent:" + dt.toString());’s not clear what’s what in this section of code
2: I don’t understand what and how the operator outputs. outBecause if you remove <<dtit and exclude it from the code altogether, leaving just out;
the output will be just "Sent:" . If I declare Qstring str = "123" and write out << str , the output doesn't change
3: how can I make something like this work?
out<<str;
Full code:
void UdpServer::slotSendDatagram()
{
    QByteArray baDatagram;
    QDataStream out(&baDatagram, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_3);
    QDateTime dt = QDateTime::currentDateTime();
    append("Sent:" + dt.toString());
    out << dt;
    m_pudp->writeDatagram(baDatagram, QHostAddress::LocalHost, 2424);
}

.cpp
#include <QtNetwork>
#include <QtGui>
#include "UdpServer.h"

// ----------------------------------------------------------------------
UdpServer::UdpServer(QWidget* pwgt /*=0*/) : QTextEdit(pwgt)
{
    setWindowTitle("UdpServer");

    m_pudp = new QUdpSocket(this);

    QTimer* ptimer = new QTimer(this);
    ptimer->setInterval(500);
    ptimer->start();
    connect(ptimer, SIGNAL(timeout()), SLOT(slotSendDatagram()));
}

// ----------------------------------------------------------------------
void UdpServer::slotSendDatagram()
{
    QByteArray baDatagram;
    QDataStream out(&baDatagram, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_3);
    QDateTime dt = QDateTime::currentDateTime();
    append("Sent:" + dt.toString());
    out << dt;
    m_pudp->writeDatagram(baDatagram, QHostAddress::LocalHost, 2424);
}

.h
#pragma once

#include <QTextEdit>

class QUdpSocket;

// ======================================================================
class UdpServer : public QTextEdit {
Q_OBJECT
private:
    QUdpSocket* m_pudp;

public:
    UdpServer(QWidget* pwgt = 0);

private slots:
    void slotSendDatagram();
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
abcd0x00, 2016-07-22
@stigmt


1: (it's a method of adding one string to the end of another, right?) append() is used like this:
In my textbook example like this append("Sent:" + dt.toString()); and it's not clear what's what in this section of code
These are different methods. In your example, the append() method of QTextEdit is used, since your UdpServer is inherited from this class.
2: It is not clear to me what and how the out operator displays <<dt.
then the output will be just "Sent:". If I declare Qstring str = "123" and write out << str, the output doesn't change
out is not an operator, but a variable of type QDataStream. The QDataStream class has redefined (they say it is overloaded, but this is wrong) the operation of a bitwise shift to the left.
You would first learn the basics of C ++, because you have questions about them, and not about Qt. You should first learn C++ and then Qt, and not vice versa.
When you do
, the variable x is written to out, because the method << is launched at out, into which the value of x is passed. And this method understands how to save this value, and knows where to save it there.
QDataStream is a serializer, it accepts any objects and casts them to a specific form, so that later on any other system from this specific type you can read these objects back and get the same data of the same types.
Why don't you write something somewhere? Because you don't understand what you're doing. What for, for example, you inherit the server from a text window? If you need the server's output, the server must send it to a separate window using a signaling system.

K
Konstantin Stepanov, 2016-07-21
@koronabora

Here is a piece from the working draft, the usage is taken from the qt documentation.

void TcpClient::sendToServer(QString data)
{
  if (_socket != Q_NULLPTR)
  {
    res = "";

    while (_socket->state() != QAbstractSocket::ConnectedState)
    {
      if (_socket->state() != QAbstractSocket::ConnectingState && _socket->state() != QAbstractSocket::HostLookupState)
      {
        _socket->connectToHost(_name, _port); // try to connect
        alreadyConnected = true;
      }
      QApplication::processEvents();
      QThread::currentThread()->msleep(NET_IO_CONNECT_DELAY);
      qDebug() << "waiting for connection";
    }

    if (alreadyConnected) // we connected to server few times ago. Let's wait
    {
      QThread::currentThread()->msleep(NET_IO_DELAY_AFTER_CONNECTION);
      alreadyConnected = false;
    }
    qDebug() << "Send to server";
    QByteArray block; 
    QDataStream out(&block, QIODevice::WriteOnly); 
    out.setVersion(QDataStream::Qt_5_6);
    out << (quint16)0; // Забиваем память под размер
    out << _realId; // записываем реальные данные
    out << data; // еще немного реальных данных
    out.device()->seek(0); // переходим на начало
    out << (quint16)(block.size() - sizeof(quint16) - sizeof(quint64)); // записываем размер сообщения
    quint64 sss = _socket->write(block); // отправляем в сокет
    if (sss < block.size()) // сокет сожрал не все
      qDebug() << "Буфер маловат будет!" << sss << " != " << block.size(); //
    else if (sss > block.size()) // сокет сожрал больше, чем необходимо
      qDebug() << "Что-то лишнее в буфере! " << sss << " != " << block.size(); //
    qDebug() << "Data written: " << data; // сокет все-таки молодец
    _socket->flush(); // выталкиваем данные в сеть
    _lastMessage = data;
    _timeOutTimer->setSingleShot(true); // ждем немного
    _timeOutTimer->start(NET_IO_DELAY); // чтобы сетевой стек успел отправить данные
  }
  else qDebug() << "Socket is null!";
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question