QTcpServer服务端问题记录

在开发Qt  socket通讯的服务端时遇到一些问题,记录下来。

1.对服务端的处理有 2种情况,

   第一种情况是在一个普通类里 new QTcpServer(); 关联newConnection信号,在相应的槽里用nextPendingConnection接收,注意,不是new QTcpSocket

接收客户端的连接

#include <QObject>

#include <QTcpServer>
#include <QTcpSocket>
 
class AppWork : public QObject
{
    Q_OBJECT
public:
    explicit AppWork(QObject *parent = nullptr);
    void DoWork();

signals:

public slots:
    void OnNewConnection();
    void OnClientConnected();
    void OnClientDisConnected();
    void OnReadClientData();
    void OnStateChanged(QAbstractSocket::SocketState);
private:
    QTcpServer *m_pServer;
    QTcpSocket *m_pSocket;

void AppWork::DoWork()

{
    m_pServer = new QTcpServer();
    connect(m_pServer,SIGNAL(newConnection()),this,SLOT(OnNewConnection()));
    m_pServer->listen(QHostAddress::Any,6000);
}
void AppWork::OnNewConnection()
{
    qDebug()<<"Received A New Connect";
    //m_pSocket = new QTcpSocket();不是new tcpsocket,而是用nextPendingConnection接收
    m_pSocket = m_pServer->nextPendingConnection();
    //connect(m_pSocket,SIGNAL(connected()),this,SLOT(OnClientConnected())); connectToHost()才会触发,这里不会触发
    connect(m_pSocket,SIGNAL(disconnected()),this,SLOT(OnClientDisConnected()));
    connect(m_pSocket,SIGNAL(readyRead()),this,SLOT(OnReadClientData()));
    connect(m_pSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(OnStateChanged(QAbstractSocket::SocketState)));
    m_pSocket->write("Hello Client,This is Server");

}



第2种方式是继承QTceServer, 重载incommingConnection
#include <QObject>
#include <QTcpServer>

#include <QTcpSocket>

class DTServer : public QTcpServer

{

public:

    DTServer();

    void incomingConnection(qintptr handle);

public slots:

    void OnDataReceive();



private:

    QTcpSocket *m_pSocket;

};




DTServer::DTServer()
{
}



void DTServer::incomingConnection(qintptr handle)

{

    qDebug()<<"Incomming Connect...";

    m_pSocket  = new QTcpSocket();

    m_pSocket->setSocketDescriptor(handle);
     //QObject::connect: No such slot QTcpServer::OnDataReceive() in ..\DTServer\dtserver.cpp:15  --》是由于 这个DTServer类忘了写Q_OBJECT了。所以识别不出来槽,需要把文 件重新移除,再添加进来
    //connect(m_pSocket,SIGNAL(readyRead()),this,SLOT(OnDataReceive()));// 注意,这里 this的定法 运行起来,当有连接到来 会提示 没有槽函数,为什么呢?子类也实现了,非要找基类去。然后说 没有
    connect(m_pSocket,&QTcpSocket::readyRead,this,&DTServer::OnDataReceive);//下面这种写法可以
    m_pSocket->write("Hello");

}
 



总结一下
第一种:处理newConnection信号,在相应的槽里m_pServer->nextPendingConnection() 获了与客户端的连接后即可进行通讯了
第二种:incomingConnection 里需要new  QTcpSocket,再setSocketDescriptor 就可以进行通讯了

posted @ 2021-02-06 13:28  伟大的厨师  阅读(187)  评论(0)    收藏  举报