2017-08-16 192 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等。他们阻止了电话!您确实需要使用信号和插槽,并连接到准备好的读取信号。这应该解决它我认为。 –