QTcpSocket描述符错误

时间:2017-08-16 17:20:04

标签: qt tcpserver

我试图了解一些有关TCP服务器和套接字的信息,并坚持这种情况。我正在创建服务器并连接套接字。但我无法获得这些套接字的正确描述符。但是当我检查nextPendingConnection时,它有正确的描述符。

这是一个简单的代码:

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

2 个答案:

答案 0 :(得分:0)

你得到-1因为套接字尚未连接。在声明QTcpSocket * s = new QTcpSocket;之后添加它,您将看到一个有效的描述符:

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

答案 1 :(得分:-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();
    });

和state是第一个HostLookupState,然后是ConnectingState,但从不是ConnectedState -

P.S。抱歉从其他帐户回复。混合它们不是故意的