C++ (Qt)#include <QObject>#include <QtNetwork>#include <QDebug> class Replyer : public QObject{ Q_OBJECTpublic: explicit Replyer(QObject *parent = 0); private: QList<QTcpSocket*> mClients; void reply(QString message); QString text; int blockSize; public slots: void newConnection(int descriptor); void newDisconnection(); //смешное название получилось :) private slots: void readData(); }; #include "replyer.h" Replyer::Replyer(QObject *parent) : QObject(parent){ blockSize = 0;} void Replyer::newConnection(int descriptor){ QTcpSocket *client = new QTcpSocket(this); if(client->setSocketDescriptor(descriptor)) { connect(client, SIGNAL(readyRead()), SLOT(readData())); connect(client,SIGNAL(disconnected()),SLOT(newDisconnection())); mClients.append(client); } else { client->deleteLater(); }}void Replyer::newDisconnection(){ foreach(QTcpSocket *client, mClients) { if (client->state()!=QAbstractSocket::ConnectedState) { qDebug() << client->socketDescriptor() << " Client Disconnected"; mClients.removeOne(client); client->deleteLater(); } }} void Replyer::readData(){ QTcpSocket *client = qobject_cast<QTcpSocket*>(sender()); QString message; while(client->bytesAvailable()) { QDataStream in(client); in.setVersion(QDataStream::Qt_4_7); if (blockSize == 0) { if (client->bytesAvailable() < (int)sizeof(quint32)) return; in >> blockSize; } if (client->bytesAvailable() < blockSize) return; in>>message; } blockSize = 0; text = message; qDebug() << message; reply(message);} void Replyer::reply(QString message){ QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_7); out << (quint32)0; out << message; out.device()->seek(0); out << (quint32)(block.size() - sizeof(quint32)); foreach(QTcpSocket* client, mClients) { client->write(block); }}
C++ (Qt)#include <QtNetwork/QTcpServer>#include <QDebug>#include "replyer.h" class MyServer : public QTcpServer{ Q_OBJECTpublic: explicit MyServer(QObject *parent = 0); void StartServer();protected: void incomingConnection(int socketDescriptor);signals: void newClient(int socketDescriptor);private: Replyer *replyer;}; #include "myserver.h" MyServer::MyServer(QObject *parent) : QTcpServer(parent){ replyer = new Replyer(); connect(this, SIGNAL(newClient(int)), replyer, SLOT(newConnection(int))); QThread *thread = new QThread(this); connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater())); replyer->moveToThread(thread); thread->start();} void MyServer::incomingConnection(int socketDescriptor){ qDebug() << socketDescriptor << " Client Connected"; emit newClient(socketDescriptor);} void MyServer::StartServer(){ if(!this->listen(QHostAddress::Any,1234)) { qDebug() << "Could not start server"; } else { qDebug() << "Listening..."; }}