/**
This is a model for threaded client/server communication using the Qt QtNetwork class library.
A threaded server is created that waits for a client connection. When the client
connects, the client sends a string (terminated by a \r) to the server. The server
reads the string and echos it back to the client. The client then prints out the string.
*/
#include "windows.h"
#include "QMutex"
#include "QThread"
#include "QTcpServer"
#include "QTcpSocket"
#include "QVector"
#include "QString"
class SocketThreadBase
{
public:
SocketThreadBase(const QString &ipAddr, const ushort port ) : mIP( ipAddr ), mPort( port )
{
mRunThread = false;
}
enum Identity {
BAD_IDENTITY,
SERVER,
CLIENT
};
virtual void startThread() = 0;
virtual void stopThread() = 0;
virtual Identity getIdentity() = 0;
protected:
QMutex mMutex;
const QString mIP;
const ushort mPort;
void setRunThread( bool newVal );
bool getRunThread();
void run();
QString readLine(QTcpSocket *socket );
int waitForInput( QTcpSocket *socket );
void writeLine( QTcpSocket *client, const QString &line );
private:
bool mRunThread;
};
class EchoServer : public SocketThreadBase, QThread
{
public:
EchoServer(const QString &ipAddr, const ushort port ) : SocketThreadBase( ipAddr, port ) {}
void startThread();
void stopThread();
Identity getIdentity() { return SERVER; }
protected:
void run();
void echoServer( QTcpSocket *client );
};