QT+= network
tcpClientSocket_.h

#ifndef TCPCLIENTSOCKET__H
#define TCPCLIENTSOCKET__H

#include <QObject>
#include <QtNetwork>
#include <QTcpSocket>

/*
*
*
*
*
* 客户端 socket
*/


class tcpClientSocket_ : public QObject
{
Q_OBJECT
public:
explicit tcpClientSocket_(QObject *parent = nullptr);

/**
* @projectName testMyClass
* @brief 连接TCP ip portNum
* @author SMY
* @date 2019-03-22
*/
bool connectTcp(QString ip,int portNum);
/**
* @projectName testMyClass
* @brief 断开连接
* @author SMY
* @date 2019-03-22
*/
void disConnect();
/**
* @projectName testMyClass
* @brief 写数据
* @author SMY
* @date 2019-03-22
*/
void write(QString str);

signals:
/**
* @projectName testMyClass
* @brief TCP断开信号
* @author SMY
* @date 2019-03-22
*/
void disConnect_signal();
/**
* @projectName testMyClass
* @brief 数据接受信号
* @author SMY
* @date 2019-03-22
*/
void receiveData(QString data);


public slots:

private:

QTcpSocket* m_socket;
void receivData();

};

#endif // TCPCLIENTSOCKET__H

tcpClientSocket_.cpp

#include "tcpclientsocket_.h"

tcpClientSocket_::tcpClientSocket_(QObject *parent) : QObject(parent)
{

m_socket = new QTcpSocket(this);

connect(m_socket,&QTcpSocket::disconnected,this
,&tcpClientSocket_::disConnect_signal);
connect(m_socket,&QTcpSocket::readyRead,this
,&tcpClientSocket_::receivData);

}

bool tcpClientSocket_::connectTcp(QString ip, int portNum)
{
m_socket->abort();

m_socket->connectToHost(ip,portNum);
if(m_socket->waitForConnected(30000))
{
return true;
}
else
return false;
}

void tcpClientSocket_::disConnect()
{
m_socket->abort();
m_socket->disconnect();
}

void tcpClientSocket_::write(QString str)
{
m_socket->write(str.toUtf8().data());
}

void tcpClientSocket_::receivData()
{
QString str = m_socket->readAll();
emit receiveData(str);
}