简体   繁体   中英

QTcpServer how to read data from client socket

I tried to implement a tcp socket server with C++/Qt. At first, the clientConnection local declaration does work.

QTcpSocket *clientConnection = tcpServer->nextPendingConnection();

However, when I tried to declare the socket with private QTcpSocket class in header file rather than declare it as local class, in order to use QTcpSocket->read in ReadReady(),I got errors. How can these problem happened?

void Server::respondNewConnection()
{
    clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, &QAbstractSocket::disconnected,
        clientConnection, &QObject::deleteLater);
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(ReadyRead()));

    clientConnection->write("[server]Welcome to server...", 100);
    qDebug() << "02[server]Welcome to server..."<<endl;
    statusLabel->setText(tr("test!"));


}

void Server::ReadyRead(){

qDebug() << "04[server]Ready to Read..." << endl;

/*
char buffer[100];
const int buffer_size = 100;
tcpSocket->read(buffer, buffer_size);
qDebug() << "05[server]Message from client: " << buffer << endl;
*/
}

I think you may need to add the forward declaration:

class QTcpSocket;

at the top of the file that you error is in.

You should read data from clientConnection object in your Server::ReadyRead function, not from tcpSocket object.

QByteArray totol_data, data_buffer;
while(1) {
    data_buffer = clientConnection->read(1024);
    if(data_buffer.isEmpty()) {
        break;
    }
    totol_data.append(data_buffer);
}
QString message_content(totol_data);

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