天天看点

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

继续阅读