Edit: Your mistake is that you open the out
data stream in ReadOnly mode, but try to write the received byte array to it:
void Server::readyRead()
{
QByteArray block;
QDataStream out(&block, QIODevice::ReadOnly); // !mistake, WriteOnly mode is needed
out << tcpSocket->readAll(); // this is write operation
//...
}
Additional: please note that there is the Serialization mechanism of Qt Data Types which is useful in such cases:
tSock->write(block); // this is write just a raw data of the block, not the "QByteArray"
You can use a stream operation to write the necessary Qt data types to a socket directly, without a convertion to QByteArray
:
// Connect firstly
tSock->connectToHost(ipAddress, portNumb.toInt());
tSock->waitForConnected();
// Then open a data stream for the socket and write to it:
QDataStream out(tSock, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << name; // write string directly without a convertion to QByteArray
// Then you may
tSock->flush();
On Client side, and then use the similar stream operation on Server side:
void Server::readyRead()
{
QString name;
QDataStream in(tcpSocket, QIODevice::ReadOnly /*or QIODevice::ReadWrite if necessary */);
in.setVersion(QDataStream::Qt_4_0);
in >> name; // read the string
//...
}
There is also possible to read/write objects another Qt's i/o devices: QFile, QSerialPort, QProcess, QBuffer and others.
Edit 2: it is not guaranteed that on readyRead
signal you'll receive full package that was sent. Therefore see the example below.
Please note, that in the real case (when you have several different packets in the client-server communication, and it is unknown what kind of the several possible packages you have received) usually there is used more complex algorithm, because the following situations may occur on the readyRead event in a communication:
- Full packet received
- Received only part of the package
- Received several packages together
The variant of the algorithm (Qt 4 Fortune Client Example):
void Client::readFortune() // on readyRead
{
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> blockSize;
}
if (tcpSocket->bytesAvailable() < blockSize)
return;
QString nextFortune;
in >> nextFortune;
//...
}
Qt 4.0 is too old version of Qt, therefore see also Qt 5.9 Fortune Client Example