why QT QTcpSocket signals does not work as expected
-
I have a simple class,
void socketTest::Test() { socket = new QTcpSocket(this); socket->setReadBufferSize(1000000); connect(socket,SIGNAL(connected()),this,SLOT(connected())); connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected())); connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead())); connect(socket,&QTcpSocket::bytesWritten,this,&socketTest::bytesWritten); qDebug()<<"Connecting..."; socket->setProxy(QNetworkProxy::NoProxy); socket->connectToHost("192.168.1.20",5017); if(!socket->waitForConnected(1000)){ qDebug()<<"Error..." <<socket->errorString(); } }
And here are the slots
void socketTest::connected(){ qDebug()<<"\r\nConnected"; socket->write("Hello world"); } void socketTest::disconnected(){ qDebug()<<"\r\nDisconnected"; } void socketTest::bytesWritten(qint64 bytes){ qDebug()<<"\r\nyeah ha"; qDebug()<<"We wrote" << bytes; } qint64 readBytes = 0; void socketTest::readyRead(){ qDebug()<<"\r\nReading...."<<readBytes; QByteArray Ba; Ba = socket->readAll(); readBytes+= Ba.size(); qDebug()<< Ba.size(); }
The problem is that, when I run the code, everything works and I would get 11 bytes written to the sever, the server has a button, if I switch it on, it will send lots of data to the client constantly until I switch it back off, so If I comment out the
//socket->write("Hello world");
I would get constant data when the socket->write is commented
The client would get all of the data continuously, but when I write something to the server (when the socket->write is not commented), when I switch the transfer data on, it would get only a few packets,
I have tested the server with hercules_3-2-8 (https://www.hw-group.com/software/hercules-setup-utility), and the sever can accept read and write data continuously,
So what I have done wrong, so the readyRead would not get any signals after a few packets If I also write something to the server.
-
@myjtag
You don't seem to have done anything wrong in your code. The implication from the code as shown is that your server stops sending after a while if it receives a "Hello world" message. That's all I can see from the behaviour you report, as unlikely as it may seem.I would put a slot on
QAbstractSocket::errorOccurred
(apparently Qt 5.15) andQAbstractSocket::stateChanged
just in case. Otherwise use WireShark to verify what is actually being sent around. -
Your "Hello, world" will be sent as exactly as many bytes as it needs, and certainly nothing like 1460 bytes. It will go out amongst any other data written to the stream (none i your example) and a bunch of other small packets handling handshakes and the like. The maximum TCP payload in a single Ethernet frame is 1460 bytes, but this is of no consequence because TCP handles fragmenting and reassembly of blocks of data making up the stream.
Are you in control of the server code? It looks to me that this is where the problem is.