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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章