在學習QT的時候,擼一下前輩開放的教程代碼。使用TcpServer的時候,出現無法監聽newConnetion的情況。
代碼如下:
void MainWindow::on_btnStart_clicked() 2 { 3 if (!tcpServer.listen(QHostAddress::Any,ui->txtPort->text().toInt())) 4 { 5 ui->labCount->setText(tr("提示:發生錯誤(%1)").arg(tcpServer.errorString())); 6 tcpServer.close(); 7 return; 8 } 9 connect(&tcpServer,SIGNAL(newConnection()),this,SLOT(AcceptConnection())); 10 11 ui->btnStart->setEnabled(false); 12 ui->btnSend->setEnabled(true); 13 ui->labCount->setText(tr("提示:正在監聽")); 14 } 15 16 void MainWindow::AcceptConnection() 17 { 18 tcpServerConnection = tcpServer.nextPendingConnection(); 20 connect(tcpServerConnection,SIGNAL(readyRead()),this,SLOT(ReadMyData())); 22 23 tcpServer.close(); //不再連接其他客戶端 24 ui->labCount->setText(tr("提示:客戶端連接成功")); 25 }
按照網上說的,試過把防火牆關閉重啟,仍然無法正常監聽,現象就是客戶端顯示連接成功,無法收到newConnection的signal。
最后發現是connect出現問題,把開啟監聽成功后的connect改成如下:
connect(&tcpServer, &QTcpServer::newConnection, this, &MainWindow::AcceptConnection);
則問題得到解決。
我的理解是:網上能搜到的代碼都是5.0之前的版本,使用SIGNAL()和SLOT()搭配確定信號和處理函數的對應;
5.0之后connect函數推薦使用上面這種情況,相對前面的方式,顯式的表明信號函數的發送主題和槽函數的歸屬。這里始終得不到newConnection,應該就是信號發送的主體可能出現問題。
同樣的,后面也出現了相同的無法收到readyRead信號的問題。
connect(tcpServerConnection,SIGNAL(readyRead()),this,SLOT(ReadMyData()));
更改成如下問題同樣得到了解決。
connect(tcpServerConnection,&QTcpSocket::readyRead ,this, &MainWindow::ReceiveData);
理解可能有偏差,但問題能夠得到解決。