2011-05-26 31 views
1

使用Qt編寫聊天。有問題。我的客戶端的QTcpSocket保持連接狀態,但服務器發出newConnection()信號。網絡會話不是必需的。這是爲什麼?下面是一些代碼:QTcpSocket問題

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(); 
} 

服務器顯示傳入的連接和客戶端不發射連接其餘處於連接狀態,那並不接收服務器消息以及.. 。 有什麼想法?

回答

4

我有同樣的問題,我找到了原因和解決方案。

connectToHost可能不會直接在主窗口的contstructor中調用。爲什麼?

原因是,此時主消息循環還沒有運行。內部QAbstractSocketPrivate::fetchConnectionParameters()得不到調用,Qt套接字超時定時器認爲連接永遠不會建立。

的解決方法是,把它叫做 「延遲」 像

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

或致電waitForConnected()connectToHost