QTcpSocket 问题

Posted

技术标签:

【中文标题】QTcpSocket 问题【英文标题】:QTcpSocket problem 【发布时间】:2011-05-26 18:42:15 【问题描述】:

使用 Qt 编写聊天。有问题。我客户端的 QTcpSocket 仍然处于连接状态,但服务器发出 newConnection() 信号。不需要网络会话。这是为什么?这是一些代码:

ChatClient::ChatClient(QObject *parent)
    : QObject(parent) 
    tcpSocket = new QTcpSocket(this);
    QNetworkConfigurationManager manager;
    if (QNetworkConfigurationManager::NetworkSessionRequired
        & manager.capabilities()) 
        qDebug() << "Network session required";
    
    connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(error(QAbstractSocket::SocketError)));
    connect(tcpSocket, SIGNAL(connected()),
            this, SLOT(requestForID()));
    connect(tcpSocket, SIGNAL(readyRead()),
            this, SLOT(receiveMessage()));
    tcpSocket->connectToHost("192.168.0.100", PORT);


void ChatClient::requestForID() 
    qDebug() << "Connected, requesting for ID";
    QByteArray segment;
    QDataStream out(&segment, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_7);
    out << (quint16)0 << ID;
    out.device()->seek(0);
    out << (quint16)(segment.size() - sizeof(quint16));
    tcpSocket->write(segment);

requestForID() 永远不会被执行

ChatServer::ChatServer(QObject *parent)
    : QObject(parent) 
    tcpServer = new QTcpServer(this);
    if (!tcpServer->listen(QHostAddress::Any, PORT)) 
        qDebug() << "Unable to start the server"
                 << tcpServer->errorString();
    
    qDebug() << "Server port" << tcpServer->serverPort();
    connect(tcpServer, SIGNAL(newConnection()),
            this, SLOT(processConnection()));

void ChatServer::processConnection() 
    qDebug() << "Incoming connection";
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
    /*connect(clientSocket, SIGNAL(readyRead()),
            this, SLOT(readData()));
    readData(clientSocket);
    connect(clientSocket, SIGNAL(disconnected()),
            clientSocket, SLOT(deleteLater()));*/
    QByteArray segment;
    QDataStream out(&segment, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_7);
    out << (quint16)0 << (quint16)Message
        << "Successfully connected";
    out.device()->seek(0);
    out << (quint16)(segment.size() - sizeof(quint16));
    clientSocket->write(segment);
    clientSocket->disconnectFromHost();

服务器显示传入的连接,客户端不发出连接保持在连接状态,也没有收到服务器消息...... 有什么想法吗?

【问题讨论】:

【参考方案1】:

我遇到了同样的问题,我找到了原因和解决方案。

connectToHost 不能在主窗口的构造函数中直接调用。为什么?

原因是,此时主消息循环尚未运行。在内部,QAbstractSocketPrivate::fetchConnectionParameters() 永远不会被调用,并且 Qt Socket Timeout Timer 认为连接永远不会建立。

解决方案要么像 in 那样将其称为“延迟”

QMetaObject::invokeMethod(this, "OnDelayedConnect", Qt::QueuedConnection);

或者在connectToHost之后调用waitForConnected()

【讨论】:

以上是关于QTcpSocket 问题的主要内容,如果未能解决你的问题,请参考以下文章

QTcpSocket 问题

为啥 QTcpSocket 不发出信号?

Qt - 当一个类中有多个 QTcpSocket 时,我如何知道哪个 QTcpSocket 发出了 readyRead 信号?

C++ Qt - QTcpSocket - 找不到文件

QTcpSocket 模拟 netcat '对话'

QTcpSocket 不加载 ssl