2016-06-13 110 views
0

我試圖用C++/Qt實現一個tcp套接字服務器。 首先,clientConnection本地聲明確實有效。QTcpServer如何從客戶端套接字讀取數據

QTcpSocket * clientConnection = tcpServer-> nextPendingConnection();

然而,當我試圖宣佈與私人類與QTcpSocket插座中的頭文件,而不是將它聲明爲局部類,爲了使用QTcpSocket->在ReadReady()讀取,我得到了錯誤。這些問題怎麼會發生?

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

「我的錯誤」 - 有哪些誤區? –

+0

@FrankOsterfeld他們顯示在不是很好的名字'enter image description here鏈接:o –

回答

0

你應該在你Server::ReadyRead功能不從的TCPSocket對象讀取clientConnection對象數據。

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

我想你可能需要添加向前聲明:

class QTcpSocket; 

在你的錯誤是在文件的頂部

相關問題