当前位置:   article > 正文

C++下TCP网络通信Tcp_Demo客户端例子(Qt+VS)_qt网络通信

qt网络通信

下面是一个简单的tcp网络通信客户端demo。

头文件TcpNetWork.h

  1. #pragma once
  2. #include <QTcpSocket>
  3. #include <QHostAddress>
  4. class TcpNetwork
  5. {
  6. public:
  7. TcpNetwork();
  8. ~TcpNetwork();
  9. void networkInit(QString ip, int port);
  10. void sendData(QString data);
  11. QString readyRead();
  12. private:
  13. QTcpSocket *socket = nullptr;
  14. };

源文件TcpNetWork.cpp

  1. #include "TcpNetwork.h"
  2. TcpNetwork::TcpNetwork()
  3. {
  4. }
  5. TcpNetwork::~TcpNetwork()
  6. {
  7. if(socket != nullptr)
  8. {
  9. socket->disconnectFromHost();
  10. socket = nullptr;
  11. }
  12. }
  13. void TcpNetwork::networkInit(QString ip, int port)
  14. {
  15. socket = new QTcpSocket();
  16. socket->connectToHost(QHostAddress(ip), port);
  17. connect(socket, &QTcpSocket::readyRead, this, &TcpNetwork::readyRead);
  18. }
  19. void TcpNetwork::sendData(QString data)
  20. {
  21. if(socket != nullptr)
  22. {
  23. socket->write(data.toUtf8().constData());
  24. }
  25. }
  26. QString TcpNetwork::readyRead()
  27. {
  28. QString data;
  29. if(socket != nullptr)
  30. {
  31. data = socket->readAll();
  32. }
  33. return data;
  34. }

实例化调用main.cpp

  1. #include "TCP_Demo.h"
  2. #include <QtWidgets/QApplication>
  3. int main(int argc, char *argv[])
  4. {
  5. QApplication a(argc, argv);
  6. TCP_Demo w;
  7. w.show();
  8. return a.exec();
  9. }

实例化调用demo头文件TCP_Demo.h

  1. #pragma once
  2. #include <QtWidgets/QMainWindow>
  3. #include "ui_TCP_Demo.h"
  4. #include "TcpNetwork.h"
  5. class TCP_Demo : public QMainWindow
  6. {
  7. Q_OBJECT
  8. public:
  9. TCP_Demo(QWidget *parent = nullptr);
  10. ~TCP_Demo();
  11. private:
  12. Ui::TCP_DemoClass ui;
  13. TcpNetwork m_TcpNetwork;
  14. };

实例化调用demo源文件TCP_Demo.cpp

  1. #include "TCP_Demo.h"
  2. TCP_Demo::TCP_Demo(QWidget *parent)
  3. : QMainWindow(parent)
  4. {
  5. ui.setupUi(this);
  6. m_TcpNetwork.networkInit("192.168.0.100", 5555);
  7. }
  8. TCP_Demo::~TCP_Demo()
  9. {}

版权声明:本文为博主原创文章,转载请附上博文链接!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/678810
推荐阅读
相关标签
  

闽ICP备14008679号