Qt客户端程序

时间:2013-07-18 09:40:17

标签: c++ qt sockets

我在Qt上为客户端编写了一个程序,用于从服务器接收数据,但它没有接收数据并将接收的字节显示为零,以下是我的程序:

// client.h

#ifndef CLIENT_H
#define CLIENT_H

#include <QObject>
#include <QString>
#include <QtNetwork/QTcpSocket>

class Client: public QObject
{
Q_OBJECT
public:
  Client(QObject* parent = 0);
  ~Client();
  void start(QString address, quint16 port);
  void send(const char*);
  void receive();
public slots:
  void startTransfer();
private:
  QTcpSocket client;
};

#endif // CLIENT_H

// client.cpp

#include "client.h"
#include <QtNetwork/QHostAddress>
#include<QIODevice>

Client::Client(QObject* parent): QObject(parent)
{
    connect(&client, SIGNAL(connected()),
    this, SLOT(startTransfer()));

    //connect(&client, SIGNAL(waitForBytesWritten()),
    //        this, SLOT(receive()));
}

Client::~Client()
{
  client.close();
}

void Client::start(QString address, quint16 port)
{
  QHostAddress addr(address);
  client.connectToHost(addr, port);
}

void Client::startTransfer()
{
  client.write("Connection Established", 22);
}

void Client::send(const char *buffer)
{
    client.write(buffer,sizeof(buffer));
}

void Client::receive()
{
    char temp[1024] = {0};
    int len = client.read(temp,client.bytesAvailable());
    printf("\tData recieved from server :: %s\n",temp);
    printf("\tSize of data received is :: %d\n",client.bytesAvailable());
    printf("\tBytes read is :: %d\n",len);
}

// main.cpp中

#include <QCoreApplication>
#include "client.h"
//#include <QApplication>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Client client;
    client.start("192.168.1.2", 9602);

    char buff[] = "Send operation performed from main";
    client.send(buff);
   // while(1)
    client.receive();

    return a.exec();
}

这里我的程序功能执行然后停止接收(可能是),当我从服务器发送任何东西时它不需要任何东西。任何建议? 如果我做了任何愚蠢的编程错误,我不是粗鲁的,因为我是新手。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用while(1)并在其中编写接收函数

答案 1 :(得分:0)

你没有得到@Merlin069的回答....你应该在信号的位置使用readyRead,你的接收函数作为插槽......它会起作用。我希望你能理解这么简单的语言。