• 4672阅读
  • 1回复

求助!QT网络编程的问题 [复制链接]

上一主题 下一主题
离线feigen
 

只看楼主 倒序阅读 楼主  发表于: 2009-10-22
求助!QT网络编程的问题
我的编译环境VS2005 ,QT-4.3.5.。按手册中的server、client例子写了两个程序,编译通过了。但是运行后就是通讯不上。
在client.cpp中设置断点,无法监视readFortune()的运行,我想是不是根本没有监视到readyRead()信号?
请各位大侠指点一下,不甚感激!

在控制台上使用netstat -a 可以看到已经建立了连接。程序代码如下:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                 server.h
//
#ifndef TEXTSERVER_H
#define TEXTSERVER_H

#include <QtGui/QMainWindow>
#include "ui_textserver.h"
#include <QtNetwork/QTcpServer>

class textServer : public QMainWindow
{
    Q_OBJECT

public:
    textServer(QWidget *parent = 0, Qt::WFlags flags = 0);
    ~textServer();

private:
    Ui::textServerClass ui;
    QTcpServer *tcpServer;
    QStringList fortunes;

private slots:
    void sendFortune();



};

#endif // TEXTSERVER_H

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                  server.cpp
//
#include "textserver.h"
#include <QtNetwork/QtNetwork>
#include <QtGui/QMessageBox>

textServer::textServer(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);

    tcpServer = new QTcpServer(this);
    if (!tcpServer->listen()) {
        QMessageBox::critical(this, tr("Fortune Server"),
            tr("Unable to start the server: %1.")
            .arg(tcpServer->errorString()));
        close();
        return;
    }

    ui.statusLabel->setText(tr("The server is running on port %1.\n"
        "Run the Fortune Client example now.")
        .arg(tcpServer->serverPort()));

    fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
        << tr("You've got to think about tomorrow.")
        << tr("You will be surprised by a loud noise.")
        << tr("You will feel hungry again in another hour.")
        << tr("You might have mail.")
        << tr("You cannot kill time without injuring eternity.")
        << tr("Computers are not intelligent. They only think they are.");

    QObject::connect(ui.quitButton, SIGNAL(clicked()), this, SLOT(close()));
    QObject::connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune()));
}

textServer::~textServer()
{

}
void textServer::sendFortune()
{
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_3);
    out << (quint16)0;
    out << fortunes.at(qrand() % fortunes.size());
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    QObject::connect(clientConnection, SIGNAL(disconnected()),
        clientConnection, SLOT(deleteLater()));

    clientConnection->write(block);
    clientConnection->disconnectFromHost();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                          clinet.h
///
#ifndef TEXTCLIENT_H
#define TEXTCLIENT_H

#include <QtGui/QMainWindow>
#include "ui_textclient.h"
#include <QtNetwork/QTcpServer>

class QDialogButtonBox;
class QLabel;
class QLineEdit;
class QPushButton;
class QTcpSocket;

class textClient : public QMainWindow
{
    Q_OBJECT

public:
    textClient(QWidget *parent = 0, Qt::WFlags flags = 0);
    ~textClient();

private:
    Ui::textClientClass ui;

    QTcpSocket *tcpSocket;
    QString currentFortune;
    quint16 blockSize;

private slots:
    void requestNewFortune();
    void readFortune();
    void displayError(QAbstractSocket::SocketError socketError);
    void enableGetFortuneButton();
};

#endif // TEXTCLIENT_H


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                client.cpp
//
#include "textclient.h"
#include <QtNetwork/QtNetwork>
#include <QtGui/QMessageBox>
#include <QtCore/QObject>


textClient::textClient(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);

    tcpSocket = new QTcpSocket(this);

    QObject::connect(ui.hostlineEdit, SIGNAL(textChanged(const QString &)),
        this, SLOT(enableGetFortuneButton()));
    QObject::connect(ui.portlineEdit, SIGNAL(textChanged(const QString &)),
        this, SLOT(enableGetFortuneButton()));
    QObject::connect(ui.getFortuneButton, SIGNAL(clicked()),
        this, SLOT(requestNewFortune()));
    QObject::connect(ui.quitButton, SIGNAL(clicked()), this, SLOT(close()));
    QObject::connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(readFortune()));
    QObject::connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
        this, SLOT(displayError(QAbstractSocket::SocketError)));
}

textClient::~textClient()
{

}

void textClient::requestNewFortune()
{
    ui.getFortuneButton->setEnabled(false);
    blockSize = 0;
    tcpSocket->abort();
    tcpSocket->connectToHost(ui.hostlineEdit->text(),
        ui.portlineEdit->text().toInt());
    ui.statusLabel->setText(tr("debug!"));
}

void textClient::readFortune()
{
    QDataStream in(tcpSocket);
    in.setVersion(QDataStream::Qt_4_3);

    if (blockSize == 0) {
        if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
            return;

        in >> blockSize;
    }

    if (tcpSocket->bytesAvailable() < blockSize)
        return;

    QString nextFortune;
    in >> nextFortune;

    if (nextFortune == currentFortune) {
        QTimer::singleShot(0, this, SLOT(requestNewFortune()));
        return;
    }

    currentFortune = nextFortune;
    ui.statusLabel->setText(currentFortune);
    ui.getFortuneButton->setEnabled(true);
}

void textClient::displayError(QAbstractSocket::SocketError socketError)
{
    switch (socketError) {
     case QAbstractSocket::RemoteHostClosedError:
         break;
     case QAbstractSocket::HostNotFoundError:
         QMessageBox::information(this, tr("Fortune Client"),
             tr("The host was not found. Please check the "
             "host name and port settings."));
         break;
     case QAbstractSocket::ConnectionRefusedError:
         QMessageBox::information(this, tr("Fortune Client"),
             tr("The connection was refused by the peer. "
             "Make sure the fortune server is running, "
             "and check that the host name and port "
             "settings are correct."));
         break;
     default:
         QMessageBox::information(this, tr("Fortune Client"),
             tr("The following error occurred: %1.")
             .arg(tcpSocket->errorString()));
    }
    ui.getFortuneButton->setEnabled(true);
}

void textClient::enableGetFortuneButton()
{
    ui.getFortuneButton->setEnabled(!ui.hostlineEdit->text().isEmpty() && !ui.portlineEdit->text().isEmpty());
    //ui.getFortuneButton->setEnabled(!ui.hostlineEdit->text().isEmpty()
    //    && !ui.portlineEdit->text().isEmpty());
}
离线feigen

只看该作者 1楼 发表于: 2009-10-27
这里应该有很多高手的,麻烦看一下可以吗?非常感谢你。
快速回复
限100 字节
 
上一个 下一个