赞
踩
下面是一个简单的tcp网络通信客户端demo。
头文件TcpNetWork.h
- #pragma once
-
- #include <QTcpSocket>
- #include <QHostAddress>
-
-
- class TcpNetwork
- {
-
- public:
- TcpNetwork();
-
- ~TcpNetwork();
-
- void networkInit(QString ip, int port);
- void sendData(QString data);
- QString readyRead();
- private:
- QTcpSocket *socket = nullptr;
- };
源文件TcpNetWork.cpp
- #include "TcpNetwork.h"
-
- TcpNetwork::TcpNetwork()
- {
- }
- TcpNetwork::~TcpNetwork()
- {
- if(socket != nullptr)
- {
- socket->disconnectFromHost();
- socket = nullptr;
- }
- }
- void TcpNetwork::networkInit(QString ip, int port)
- {
- socket = new QTcpSocket();
- socket->connectToHost(QHostAddress(ip), port);
- connect(socket, &QTcpSocket::readyRead, this, &TcpNetwork::readyRead);
- }
- void TcpNetwork::sendData(QString data)
- {
- if(socket != nullptr)
- {
- socket->write(data.toUtf8().constData());
- }
- }
- QString TcpNetwork::readyRead()
- {
- QString data;
- if(socket != nullptr)
- {
- data = socket->readAll();
- }
- return data;
- }
实例化调用main.cpp
- #include "TCP_Demo.h"
- #include <QtWidgets/QApplication>
-
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- TCP_Demo w;
- w.show();
- return a.exec();
- }
实例化调用demo头文件TCP_Demo.h
- #pragma once
-
- #include <QtWidgets/QMainWindow>
- #include "ui_TCP_Demo.h"
- #include "TcpNetwork.h"
-
- class TCP_Demo : public QMainWindow
- {
- Q_OBJECT
-
- public:
- TCP_Demo(QWidget *parent = nullptr);
- ~TCP_Demo();
-
- private:
- Ui::TCP_DemoClass ui;
- TcpNetwork m_TcpNetwork;
- };
实例化调用demo源文件TCP_Demo.cpp
- #include "TCP_Demo.h"
-
-
- TCP_Demo::TCP_Demo(QWidget *parent)
- : QMainWindow(parent)
- {
- ui.setupUi(this);
- m_TcpNetwork.networkInit("192.168.0.100", 5555);
- }
-
- TCP_Demo::~TCP_Demo()
- {}
版权声明:本文为博主原创文章,转载请附上博文链接!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。