Qt客户程序

Qt client programme

本文关键字:程序 客户 Qt      更新时间:2023-10-16

我在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

//客户端.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 :: %sn",temp);
    printf("tSize of data received is :: %dn",client.bytesAvailable());
    printf("tBytes read is :: %dn",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();
}

在这里,我的程序函数执行,然后停止接收(可能是),当我从服务器发送任何东西时,它不需要任何东西。有什么建议吗?如果我犯了任何愚蠢的编程错误,请不要无礼,因为我是新手。

您没有得到@Merlin069的答案。。。。你应该使用readyRead在信号的位置和你的receiveve函数作为插槽。。。它会起作用的。我希望你能理解这种简单的语言。

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