Server.h
class Server : public QTcpServer
{
Q_OBJECT
public:
Server(QObject *parent = 0);
~Server();
void startServer();
protected:
void incomingConnection( qintptr handle );
private:
QThreadPool *pool;
};
Server.cpp
Server::Server(QObject *parent) :
QTcpServer(parent)
{
pool = new QThreadPool(this);
pool->setMaxThreadCount(5);
}
Server::~Server()
{
delete pool;
}
void Server::startServer()
{
if(listen(QHostAddress::Any, 8080)){
qDebug() << "Server started";
}else{
qDebug() << "Server did not start!";
}
}
void Server::incomingConnection(qintptr handle)
{
Runnable *runnable = new Runnable();
runnable->setAutoDelete(true);
connect(runnable->dataBase, SIGNAL(sendMessageToEmail(QStringList)), this, SLOT(sendMail(QStringList)));
runnable->socketDescriptor = handle;
pool->start(runnable);
}
Runnable.cpp
...
void Runnable::run()
{
if(!socketDescriptor){
return;
}
socket = new QTcpSocket;
socket->setSocketDescriptor(socketDescriptor);
QObject::connect(&(*socket), SIGNAL(disconnected()), this, SLOT(disconected()));
outStream << quint16(0);
while(socket->isOpen())
{
socket->waitForReadyRead();
if(socket->bytesAvailable() == 0){
continue;
}
onReadyRead();
}
}
void Runnable::sendToUser()
{
outStream.device()->seek(0);
outStream << quint16(arrByteOut.size() - sizeof(quint16));
socket->write(arrByteOut);
socket->waitForBytesWritten();
}
void Runnable::onReadyRead()
{
QDataStream in(socket);
in.setVersion(QDataStream::Qt_5_5);
if(socket->isOpen())
{
if(nextBlockSize == 0){
in >> nextBlockSize;
}
if(socket->bytesAvailable() < nextBlockSize){
return;
}
if(socket->isOpen()){
queryDefinition(in);
nextBlockSize = 0;
}
}
}
...
提前致谢。