2017-08-16 159 views
-1

我想了解一些關於TCP服務器和套接字,並堅持這種情況。我正在創建服務器並將套接字連接到它。但是我無法爲這些套接字獲取正確的描述符。但是,當我檢查nextPendingConnection時,它具有正確的描述符。QTcpSocket描述符錯誤

下面是一個簡單的代碼:

QTcpServer server; 
server.listen(QHostAddress::LocalHost, 2500); 

QObject::connect(&server, &QTcpServer::newConnection, [&] { 
    qDebug()<<"New connection recieved!"; 
    QTcpSocket* connection = server.nextPendingConnection(); 
    qDebug()<<"socket descriptor: "<<connection->socketDescriptor(); // here i have some correct descriptor 
    connection->waitForReadyRead(); 
}); 

QTcpSocket *s = new QTcpSocket; 
qDebug()<<s->socketDescriptor(); // here i get -1 
s->connectToHost(QHostAddress::LocalHost, 2500); 
qDebug()<<s->socketDescriptor(); // and here i get -1 

回答

0

你得到,因爲套接字尚未連接-1。收藏此聲明*與QTcpSocket S =新後與QTcpSocket,和你會看到一個有效的描述符:

QObject::connect(s, &QTcpSocket::connected, [&] { 
    qDebug()<<"socket descriptor (c): "<<s->socketDescriptor(); 
}); 
-1

羅爾夫,我想就像你說的話。但信號甚至沒有發射。

QTcpSocket *s = new QTcpSocket; 

    QObject::connect(s, &QTcpSocket::connected, [&] { 
     qDebug()<<" --- socket descriptor (c): "<<s->socketDescriptor(); 
    }); 

    s->connectToHost(QHostAddress::LocalHost, 2500); 

不過,我從上新的連接服務器的插槽......奇怪

另外,我補充說:

QObject::connect(s, &QTcpSocket::stateChanged, [&] { 
     qDebug()<<" --- socket state (c): "<<s->state(); 
    }); 

和狀態是第一HostLookupState然後ConnectingState但從未ConnectedState -

ps抱歉從另一個帳戶回答。混合他們不是故意的

+0

奇怪,快速測試(在MacOS)和它的工作對我來說: socket描述:3 socket描述符(C):21 你可以使用Wireshark檢查,如果三次握手去通過和一些系統工具(取決於您的操作系統)操作系統認爲套接字狀態是什麼。 –

+0

嗨,Rolf 添加「waitForConnected」後我有新的情況。這裏是代碼: s-> connectToHost(QHostAddress :: LocalHost,2500); if(!s-> waitForConnected(5000)) qDebug()<<「Error:」<< s-> errorString(); } 所以,我從套接字方法接收描述符,但它們與tcp服務器給我的不同。你有什麼想法嗎? –

+0

對不起,我之前沒有看到這個,因爲我沒有在我的早期試用中使用它。你不應該使用waitForReadyRead等。他們阻止了電話!您確實需要使用信號和插槽,並連接到準備好的讀取信號。這應該解決它我認爲。 –