Search code examples
qtqtcpsocketqtcpserver

How to send and read string lines via QTcpSocket?


I try to send strings from client to server line by line in a foreach loop:

foreach(QString s, stringlist)
   client.sendMessage(s);

But the client receives only first string. When I remove "\n" from a string, server receives a bunch of strings merged together in one big string. I thought that adding "\n" would divide the data to strings which I can read with readLine(). What have I missed?

My client

class cClient:public QTcpSocket
{
public:
    void sendMessage(QString text)
    {
        text = text + "\n";
        write(text.toUtf8());        
    }
};

and server:

class pServer:public QTcpServer
{
    Q_OBJECT
public:
    pServer()
    {
        connect(this,SIGNAL(newConnection()),SLOT(slotNewConnection()));
    }

public slots:
    void slotNewConnection()
    {
        QTcpSocket* c = nextPendingConnection();
        connect(c,SIGNAL(readyRead()),this, SLOT(readData()));
    }

    void readData()
    {
        QTcpSocket* conn = qobject_cast<QTcpSocket*>(sender());
        QString data = QString(conn->readLine());
    }
};

Solution

  • You are probably receiving more than one line at the time but only reading the first one. Read as many lines as available by checking with canReadLine. Something like that:

    void readData()
    {
        QTcpSocket* conn = qobject_cast<QTcpSocket*>(sender());
        QStringList list;
        while (conn->canReadLine())
        {
            QString data = QString(conn->readLine());
            list.append(data);
        }     
    }