Qt开发的TCP客户端和服务器

前言

自己写的demo测试程序,已通过网络调试助手验证程序是可行的,该程序界面可以切换TCP客户端和服务器,可以接收和发送信息到网络调试助手,可以切换不同的语言,项目下载地址:https://download.csdn.net/download/linyibin_123/86266759

核心代码参考

tcpcontrol.h
#ifndef TCPCONTROL_H
#define TCPCONTROL_H

#include 
#include 
#include 
#include 
#include 
#include 

#define MY_DEBUG  qDebug()  << "[" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz") << "]" << "[" << __FILE__ << ":" << __FUNCTION__ << ":" << __LINE__ << "] "

class TcpControl : public QObject
{
    Q_OBJECT
public:
    TcpControl();
    static TcpControl* getInstance();

signals:
    void sigConnectResult(bool bResult);
    void sigRecvContent(QByteArray data);

public slots:
    void slotConnectToServer(const QString& nIp, quint16 nPort);
    void slotStartListen(quint16 nPort);
    void slotStopListen();
    void slotInitSocket();
    void slotNewConnection();
    bool slotReconnect();
    void slotDisconnect();
    void slotSendContent(QByteArray data);

private slots:
    void slotStateChanged(QAbstractSocket::SocketState state);
    void slotReadyRead();

private:
    void initServer();

private:
    QString m_ip;
    quint16 m_nPort;
    QTcpSocket* m_pSocket = nullptr;
    QTcpServer* m_pServer = nullptr;
    bool m_bTcpConnected;
    QByteArray m_receiveData;

    static TcpControl* ms_pInstance;


};

#endif // TCPCONTROL_H
tcpcontrol.cpp
#include "tcpcontrol.h"

TcpControl::TcpControl()
{
}

TcpControl* TcpControl::ms_pInstance = nullptr;
TcpControl *TcpControl::getInstance()
{
    if(ms_pInstance == nullptr)
    {
        ms_pInstance = new TcpControl;
    }
    return ms_pInstance;
}

void TcpControl::slotConnectToServer(const QString &nIp, quint16 nPort)
{
    m_ip = nIp;
    m_nPort = nPort;

    bool bResult = false;
    if(m_pSocket == nullptr)
    {
        slotInitSocket();
    }

    if(m_pSocket)
    {
        m_pSocket->connectToHost(nIp, nPort);
        bResult = m_pSocket->waitForConnected();
        if(bResult)
        {
            m_bTcpConnected = true;
        }
    }
}

void TcpControl::slotStartListen(quint16 nPort)
{
    m_nPort = nPort;
    if(m_pServer == nullptr)
    {
        initServer();
    }
    bool bRes = m_pServer->listen(QHostAddress::Any, m_nPort);
    if(bRes)
    {
        MY_DEBUG << "Listen Success.";
    }
    else
    {
        MY_DEBUG << "Listen Failed.";
    }
    emit sigConnectResult(bRes);
}

void TcpControl::slotStopListen()
{
    if(m_pServer)
    {
        m_pServer->close();
        m_pServer->deleteLater();
        m_pServer = nullptr;
    }
    m_bTcpConnected = false;
}

void TcpControl::slotInitSocket()
{
    if(m_pSocket == nullptr)
    {
        m_pSocket = new QTcpSocket(this);
    }
    if(m_pSocket)
    {
        connect(m_pSocket, &QTcpSocket::stateChanged,
                this, &TcpControl::slotStateChanged);
        connect(m_pSocket, &QTcpSocket::readyRead,
                this, &TcpControl::slotReadyRead);
    }
}

void TcpControl::slotNewConnection()
{
    if(m_pServer->hasPendingConnections())
    {
        m_pSocket = m_pServer->nextPendingConnection();
        if(m_pSocket != nullptr)
        {
            connect(m_pSocket, &QTcpSocket::stateChanged,
                    this, &TcpControl::slotStateChanged);
            connect(m_pSocket, &QTcpSocket::readyRead,
                    this, &TcpControl::slotReadyRead);

            m_bTcpConnected = true;
        }
    }
}

bool TcpControl::slotReconnect()
{
    bool bRes = false;
    if(m_pSocket)
    {
        m_pSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
        m_pSocket->connectToHost(m_ip, m_nPort);
        bRes = m_pSocket->waitForConnected();
    }
    return bRes;
}

void TcpControl::slotDisconnect()
{
    if(m_pSocket)
    {
        m_pSocket->disconnectFromHost();
        m_pSocket->deleteLater();
        m_pSocket = nullptr;
    }
}

void TcpControl::slotSendContent(QByteArray data)
{
    if(m_pSocket != nullptr)
    {
        m_pSocket->write(data);
    }
}

void TcpControl::slotStateChanged(QAbstractSocket::SocketState state)
{
    if(state == QAbstractSocket::ConnectedState)
    {
        m_bTcpConnected = true;
    }
    else if(state == QAbstractSocket::UnconnectedState)
    {
        m_bTcpConnected = false;
    }
}

void TcpControl::slotReadyRead()
{
    if(m_pSocket)
    {
        m_receiveData.append(m_pSocket->readAll());
        sigRecvContent(m_receiveData);
    }
}

void TcpControl::initServer()
{
    m_pServer = new QTcpServer(this);
    if(m_pServer)
    {
        connect(m_pServer, &QTcpServer::newConnection, this, &TcpControl::slotNewConnection);
    }
}

结果展示:

Qt开发的TCP客户端和服务器_第1张图片

你可能感兴趣的:(qt,qt,tcp/ip,服务器)