QTcpServer如何从客户端套接字读取数据

时间:2016-06-13 02:25:07

标签: c++ qt sockets

我尝试用C ++ / Qt实现一个tcp套接字服务器。 首先,clientConnection本地声明确实有效。

  

QTcpSocket * clientConnection = tcpServer-> nextPendingConnection();

但是,当我尝试在头文件中声明带有私有QTcpSocket类的套接字而不是将其声明为本地类时,为了在ReadReady()中使用QTcpSocket->读取,我得到了错误。这些问题怎么会发生?

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;
*/
}

2 个答案:

答案 0 :(得分:1)

我认为您可能需要添加前向声明:

class QTcpSocket;

位于错误所在文件的顶部。

答案 1 :(得分:0)

您应该从Server::ReadyRead函数中的clientConnection对象读取数据,而不是从tcpSocket对象读取数据。

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);