简体   繁体   English

如何使用 QTcpSocket (Qt4.7) 读取完整数据

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

I created a TcpServer in order to receive data from a client.我创建了一个 TcpServer 以便从客户端接收数据。 The client sends a lot of messages and I would like to read them.客户端发送了很多消息,我想阅读它们。 So far my TcpServer.cpp looks like this :到目前为止,我的 TcpServer.cpp 看起来像这样:



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 !我知道我的 getData 函数需要更多才能接收所有内容,但我不明白这样做所需的步骤。如果有人能给我一些指点,我将不胜感激!

TCP is a transport protocol which is stream oriented. TCP是一种面向流的传输协议。 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. TCP 还没有定义消息,因为它又是一个连续的数据流。

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.您需要一个应用层协议,例如 http,然后定义“消息”并为您提供有关如何阅读完整消息的进一步说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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