简体   繁体   中英

How to read complete data using QTcpSocket (Qt4.7)

I created a TcpServer in order to receive data from a client. The client sends a lot of messages and I would like to read them. So far my TcpServer.cpp looks like this :



void TcpServer::serverStart()
{
    server = new QTcpServer(this);
    if (!server->listen(QHostAddress("192.168.x.x"), 48583))
    {
        qDebug() << "Not listening";
        server->close();
        delete server;
        return;
    }
    else {
        qDebug() << "Listening";
    }

connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));


}



void TcpServer::newConnection()
{

    socket = server->nextPendingConnection();
    qDebug() << "Client connected";

    connect(socket, SIGNAL(readyRead()), this, SLOT(getData()));
    connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
}


void TcpServer::getData()
{

QByteArray buffer;

while (socket->bytesAvailable())
    {
        buffer.append(socket->readAll());
       }
qDebug() << buffer;
    }




void TcpServer::serverStop()
{
    server->close();
    delete server;
}

I know my getData function needs a lot more in order to receive everything but I don't understand the steps needed to do that.If someone could give me some pointers I would be grateful !

TCP is a transport protocol which is stream oriented. Imagine it as being a continuous flow of data. There are no messages defined by TCP yet, because once again it is a continuous flow of data.

I'm taking from your comment that you are not using any application layer protocol. You need an application layer protocol, like eg http, which is then defining "messages" and giving you further instructions on how to read a complete message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM