i'm trying to develop a simple server with basic authentication, i have the following code:
socket = new QTcpSocket();
connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()),Qt::DirectConnection);
connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected()),Qt::DirectConnection);
check_user();
....... and check_user() is
socket->write("Please enter username:");
socket->flush();
QStringList list;
while (socket->canReadLine())
{
QString data = QString(socket->readLine());
if ( data == "\r\n" )
break;
list.append(data);
}
qDebug()<<list;
but this don't wait for user input and go further. I would like that this function wait for user input for a string of variable lenght till carriage return. but how?
You can connect a slot to the readyRead()
signal of the socket and handle the input there.
(https://doc.qt.io/qt-5/qiodevice.html#readyRead)
But for that to work you will need an event loop running in the thread the socket lives in.
(https://doc.qt.io/archives/qt-4.8/qeventloop.html)
Another solution would be to use waitForReadyRead(-1)
of the socket. This would block the thread and emit the readyRead()
signal. The function will return true
if the signal gets emitted. But you would also need a running event loop.
(https://doc.qt.io/qt-5/qabstractsocket.html#waitForReadyRead)