PDA

View Full Version : Multithreaded Server



niol1000
24th February 2010, 15:51
I'm writing a simple multithreaded server and I wind up with this code:


ServerThread::ServerThread(int handle, QObject* parent)
:QThread(parent)
{
m_descriptor = handle;
init();
}

void ServerThread::run()
{
m_socket = new QTcpSocket();

if(!m_socket->setSocketDescriptor(m_descriptor))
{
qDebug("Socket Error!");
exit(-1);
}

connect(m_socket, SIGNAL(readyRead()), this, SLOT(ready()),Qt::DirectConnection);

m_socket->waitForReadyRead(10000);
}

void ServerThread::ready()
{
disconnect(m_socket, SIGNAL(readyRead()));

//Check incoming command
if(m_socket->canReadLine())
{
QStringList tokens = QString(m_socket->readLine()).split(QRegExp("[\r\n][\r\n]*"));

switch(map.value(tokens[0]))
{
case GETA:
doSomeThing();
break;
case GETB:
doSomeThing();
break;
case QUIT:
m_socket->disconnectFromHost();
break;
default:
m_socket->disconnectFromHost();
return;
}
}
}

The above code works, but is it a good way to do it ?

wysota
24th February 2010, 17:33
There is more than one path that leads to the same goal... I don't like the part where you read the tokens as you expect to always get one line at a time which is a false assumption. You should have a while(m_socket->canReadLine()) loop there. Also the splitting regexp seems odd.