勿喷, 公司上不了gitee,下载不了资源, 之前的代码下载不了,只能这样,便于工作中抄写代码。
#include <QCoreApplication>
#include"tsever.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TSever sever(QHostAddress::Any ,8080);
sever.start(2);
return a.exec();
}
#ifndef TSEVER
#define TSEVER
#include<QTcpServer>
#include<QThreadPool>
#include"worktask.h"
class TSever : public QTcpServer
{
public:
explicit TSever(const QHostAddress &address ,const quint16 &port,QObject *parent = nullptr);
void start(const int & maxthread);
private:
QHostAddress _address;
quint16 _port;
QThreadPool *Pool;
protected:
void incomingConnection(qintptr handle);
};
#endif
#include"tsever.h"
TSever::TSever(const QHostAddress &address, const quint16 &port, QObject *parent):
_address(address),
_port(port),
QTcpServer(parent)
{
Pool = new QThreadPool;
}
void TSever::start(const int& maxthread)
{
this->listen(_address,_port);
Pool->setMaxThreadCount(maxthread);
qDebug()<<"sever start...";
}
void TSever::incomingConnection(qintptr handle)
{
ThreadTask * task = new ThreadTask(handle);
Pool->start(task);
Pool->releaseThread();
task->setAutoDelete(true);
}
#ifndef WORKTASK
#define WORKTASK
#include<QRunnable>
#include<QObject>
#include<QTcpSocket>
#include<QThread>
#include<QDebug>
#include<QEventLoop>
#include<iostream>
#include<map>
#include<QDir>
#include<QCryptographicHash>
class ThreadTask : public QObject,public QRunnable
{
Q_OBJECT
public:
explicit ThreadTask(const qintptr &hander ,QObject *parent = nullptr);
~ThreadTask() override;
protected:
void run() override;
private:
QTcpSocket *Sock;
qintptr _hander;
public slots:
void readdata();
void stateChanged(QAbstractSocket::SocketState state);
void error(QAbstractSocket::SocketError error);
};
#endif
#include"worktask.h"
ThreadTask::ThreadTask(const qintptr &hander, QObject *parent):_hander(hander),
QObject(parent),
QRunnable()
{
}
ThreadTask::~ThreadTask()
{
try {
if(Sock->isValid()) Sock->close();
if(Sock) delete Sock;
} catch (...) {
qDebug()<<"ThreadTask clear error ...";
}
}
void ThreadTask::run()
{
if(!_hander) return;
QEventLoop Loop;
Sock = new QTcpSocket;
Sock->setSocketDescriptor(_hander);
connect(Sock,&QTcpSocket::readyRead,this,&ThreadTask::readdata,Qt::DirectConnection);
connect(Sock,&QTcpSocket::disconnected,&Loop,&QEventLoop::quit);
connect(Sock,&QTcpSocket::stateChanged,this,&ThreadTask::stateChanged,Qt::DirectConnection);
connect(Sock,SIGNAL(error(AbstractSocket::SocketError)),this,SLOT(error(QAbstractSocket::SocketError)));
Loop.exec();
}
void ThreadTask::readdata()
{
QByteArray data;
qint64 length = Sock->bytesAvailable();
data = Sock->read(length);
qDebug()<<data;
return ;
}
void ThreadTask::stateChanged(QAbstractSocket::SocketState state)
{
qDebug()<<"aaaaaaaaaaaaaaaaaaaaaa";
if(state == QAbstractSocket::ClosingState)
{
emit Sock->disconnected();
}
}
void ThreadTask::error(QAbstractSocket::SocketError error)
{
emit Sock->disconnected();
}