QTcpServer实现多线程-采用重写incommingConnection方式

 1 #include <QCoreApplication>
 2 #include "appwork.h"
 3 int main(int argc, char *argv[])
 4 {
 5     QCoreApplication a(argc, argv);
 6     AppWork app;
 7     app.DoWork();
 8 
 9     return a.exec();
10 }
11 
12 #include <QObject>
13 #include <QTcpServer>
14 #include <QTcpSocket>
15 class DTServer : public QTcpServer
16 {
17     Q_OBJECT
18 public:
19     DTServer();
20     void incomingConnection(qintptr handle);
21 public slots:
22     void OnDataReceive();
23     void OnClientConnected();
24     void OnClientDisconnected();
25     void OnStateChanged(QAbstractSocket::SocketState);
26     void ConnectError(QAbstractSocket::SocketError);
27 
28 private:
29     QTcpSocket *m_pSocket;
30 };
31 
32 #endif // DTSERVER_H
33 
34 #include "dtserver.h"
35 #include <QDebug>
36 DTServer::DTServer():QTcpServer()
37 {
38 }
39 //为什么还要重写这个函数呢?。其实有一点可以看到,默认的socket都是创建在主线程中的,
40 //我们想要在子线程处理网络操作就没办法了。而重写这个函数,
41 //得到handle可以在子线程中创建socket,socket自己创建自己管理主动权在手也能玩出更多的花样。
42 void DTServer::incomingConnection(qintptr handle)
43 {
44     qDebug()<<"Incomming Connect...";
45     m_pSocket  = new QTcpSocket();
46     m_pSocket->setSocketDescriptor(handle);
47 
48     connect(m_pSocket, SIGNAL(connected()), this, SLOT(OnClientConnected()));
49     connect(m_pSocket,SIGNAL(readyRead()),this,SLOT(OnDataReceive()));
50     connect(m_pSocket, SIGNAL(disconnected()), this, SLOT(OnClientDisconnected()));
51     connect(m_pSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(OnStateChanged(QAbstractSocket::SocketState)));
52     connect(m_pSocket, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(ConnectError(QAbstractSocket::SocketError)));
53     addPendingConnection(socket);//暂时不知道为什么要加这一句,有什么作用?不写不写 都不影响与客户端的通讯
54     m_pSocket->write("Hello");
55 }
56 
57 void DTServer::OnDataReceive()
58 {
59     qDebug()<<"Read:"<<m_pSocket->readAll();
60 }
61 
62 void DTServer::OnClientConnected()
63 {
64     qDebug()<<"Connected Ok"<<m_pSocket->peerAddress();
65 }
66 
67 void DTServer::OnClientDisconnected()
68 {
69     qDebug()<<"Dis Connected";
70 }
71 
72 void DTServer::OnStateChanged(QAbstractSocket::SocketState  state)
73 {
74     qDebug()<<"state"<<state;
75 }
76 
77 void DTServer::ConnectError(QAbstractSocket::SocketError error)
78 {
79     qDebug()<<"Connect Error:"<<error;
80 }

上面是未添加线程,

添加线程的思路:

实现qtcpserver服务端 有2种方式,这里选择使用继承QTcpServer,并重写incommingConnection函数

采用这种方式,需要在incommingConnection里new 一个 qtcpsocket,

由于想把 客户端的这个连接单独放到一个线程,所以根据QTcpServer中文档要求,需要把描述符传递到另一个类再处理,

就不能直接在incommingConnection中new QTcpSocket了,

那我们添加个类DTSocket,继承于QTcpSocket

 

posted @ 2021-02-06 22:04  伟大的厨师  阅读(1319)  评论(0)    收藏  举报