QTcpSocket问题

时间:2011-05-26 18:42:15

标签: qt qtcpsocket

使用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 个答案:

答案 0 :(得分:4)

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

可能不会直接在主窗口的contstructor中调用

connectToHost。为什么呢?

原因是,此时主消息循环尚未运行。内部QAbstractSocketPrivate::fetchConnectionParameters()永远不会被调用,Qt套接字超时定时器认为连接永远不会建立。

解决方案是将其称为“延迟”,如

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

或者在waitForConnected()

之后致电connectToHost