天天看點

QT QTcpServer 和 QTcpSocket搭建的TCP服務端,單用戶端接入

使用QTcpServer和QTcpSocket建立單用戶端接入的tcp伺服器比較友善,不需要繼承QTcpServer類和QTcpSocket類,但是需要繼承QObject類,因為需要使用到信号與槽。。。

在頭檔案中建立:

QTcpServer類用于監聽端口

QTcpSocket類用于 服務端和用戶端資料的傳遞

當QTcpServer監聽到一個連接配接時,會自動觸發newConnection()信号。。。

通過newConnection()信号觸發自定義槽函數newConnectionSlot()。。。

connect(tcpserver, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));

當用戶端發送資料給服務端時,QTcpSocket自動觸發readyRead()信号。

通過readyRead()信号觸發自定義槽函數dataReceived();

connect(tcpsocket, SIGNAL(readyRead()),this, SLOT(dataReceived()));

當用戶端斷開連接配接時,QTcpSocket自動觸發disconnected()信号。

通過disconnected()信号觸發槽函數deleteLater()。防止記憶體洩漏。。

connect(tcpsocket, SIGNAL(disconnected()), tcpsocket, SLOT(deleteLater()));

//頭檔案

#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <QTcpServer>
#include <QTcpSocket>

class TcpServer : public QObject    //繼承QObject類
{
    Q_OBJECT                        //必須添加Q_OBJECT,為了使用信号與槽
public:
    TcpServer();
    int run();                        //伺服器啟動

private:
    QTcpServer *tcpserver;
    QTcpSocket *tcpsocket;

protected slots:                        //槽
    void newConnectionSlot();
    void dataReceived();
};
           

cpp檔案中,run()函數中開啟伺服器的監聽 

在newConnectionSlot()中,通過nextPendingConnection()擷取到QtcpSocket對象,通過QtcpSocket擷取資料。

而且改代碼中隻能實作一個QtcpSocket對象傳遞資料,因為當有新的連接配接接入時,nextPendingConnection()再次被調用,QtcpSocket對象位址被修改,指向新的QtcpSocket對象。。。

需要實作單伺服器多用戶端,我們需要給QtcpSocket對象打上标記(辨別符),用來區分誰是誰,這樣才能區分接收到資料是誰傳遞過來的(下一章讨論)。。

//CPP檔案

#include "tcpserver.h"
#include <QDebug>
#include <QFile>

TcpServer::TcpServer()
{
    tcpserver = new QTcpServer();
    connect(tcpserver, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
}

int TcpServer::run()
{
    if (tcpserver->listen(QHostAddress::Any, 3230))
    {
        qDebug()<<"[TcpServer]-------------------------------------------------listen sucess"<<endl;
    }
    else
    {
        qDebug()<<"[TcpServer]-------------------------------------------------listen faile"<<endl;
    }
}

void TcpServer::newConnectionSlot()
{
     qDebug()<<"[TcpServer]-------------------------------------------------new Connection !!!"<<endl;
     tcpsocket = tcpserver->nextPendingConnection();
     qDebug()<<"From ---> "<<tcpsocket->peerAddress()<<":"<<tcpsocket->peerPort()<<endl;

     //接收到新資料的信号以及連接配接斷開的信号
     connect(tcpsocket, SIGNAL(readyRead()),this, SLOT(dataReceived()));
     connect(tcpsocket, SIGNAL(disconnected()), tcpsocket, SLOT(deleteLater()));
}

void TcpServer::dataReceived()
{
    QByteArray buffer;
    //讀取緩沖區資料
    buffer = tcpsocket->readAll();
    if(!buffer.isEmpty())
    {
        QString command =  QString::fromLocal8Bit(buffer);
        qDebug()<<"[command]:" << command <<endl;
    }
}
           

繼續閱讀