покажи код
Вот код.
#include <QtCore/QCoreApplication>
#include <QTcpSocket>
#include <QTcpServer>
#include <QDate>
#include <QTime>
#include <iostream>
using namespace std;
class TripServer : public QTcpServer
{
Q_OBJECT
public:
TripServer(QObject *parent = 0);
private:
void incomingConnection(int socketId);
};
TripServer::TripServer(QObject *parent)
:QTcpServer(parent)
{
}
class ClientSocket : public QTcpSocket
{
Q_OBJECT
public:
ClientSocket(QObject *parent = 0);
private slots:
void readClient();
public:
void generateRandomTrip(const QString &from,const QString &to, const QDate &date, const QTime &time);
quint16 nextBlockSize;
};
ClientSocket::ClientSocket(QObject *parent)
:QTcpSocket(parent)
{
connect(this, SIGNAL(readyRead()), this, SLOT(readClient()));
connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater()));
nextBlockSize = 0;
}
void TripServer::incomingConnection(int socketID)
{
ClientSocket *socket = new ClientSocket(this);
socket->setSocketDescriptor(socketID);
}
void ClientSocket::readClient()
{
QDataStream in(this);
in.setVersion(QDataStream::Qt_4_5);
if (nextBlockSize == 0)
{
if(bytesAvailable() < sizeof(quint16))
return;
in >> nextBlockSize;
}
if(bytesAvailable() < nextBlockSize)
return;
quint8 requestType;
QString from;
QString to;
QDate date;
QTime time;
quint8 flag;
in >> requestType;
if (requestType == 'S')
{
in >> from >> to >> date >> time >> flag;
srand(from.length() * 3600 + to.length() * 60 + time.hour());
int numTrips = rand() % 8;
for(int i = 0; i < numTrips; ++i)
generateRandomTrip(from, to, date, time);
QDataStream out(this);
out << quint16(0xFFFF);
}
close();
}
void ClientSocket::generateRandomTrip(const QString &from, const QString &to, const QDate &date, const QTime &time)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_5);
quint16 duration = rand() % 200;
out << quint16(0) << date << time << duration << quint8(1)
<< QString ("InterCity");
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
write(block);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TripServer server;
if(!server.listen(QHostAddress::Any, 6178)){
cerr << "Failed to bind to port" << endl;
return 1;
}
else
a.quit();
return a.exec();
}