1

I wrote a program for client on Qt to receive data from server but it is not receiving data and showing received bytes as zero,following is my program:

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

Here my program function executes and then stops receiving(may be),when I send any thing from server it doesn't take anything.Any suggestions? Plz don't be rude if I have done any silly programming mistake because I'm newbie.

4

2 回答 2

0

你没有得到@Merlin069 的答案......你应该在信号的地方使用 readyRead 并且你的接收功能作为插槽......它会起作用。我希望这种简单的语言对你来说是可以理解的。

于 2013-07-18T11:18:48.413 回答
0

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

于 2013-07-18T10:01:21.753 回答