Here's an example:
class ClientHandler
: public QObject{
Q_OBJECT
public:
ClientHandler
( QTcpSocket *socket
) : _socket
( socket
) {
connect( _socket, SIGNAL( disconnected() ), this, SLOT( disconnected() ) );
connect( _socket, SIGNAL( readyRead() ), this, SLOT( readyRead() ) );
// ...
}
private slots:
// this method will be invoked when client disconnects
void disconnected()
{
// ...
deleteLater(); // delete ClientHandler instance
}
// this will be invoked when client sends some data (remember that you receive a stream of bytes )
void readyRead()
{
_buffer.append( _socket->readAll() );
// while there is at least one complete message in the buffer:
// parse & process the message
// remove that message from the buffer
}
private:
};
// ...
void mythread::processConnection()
{
QTcpSocket *clientConnection
= tcpServ
->nextPendingConnection
();
if( clientConnection != 0 ) {
new ClientHandler( clientConnection );
}
}
class ClientHandler : public QObject
{
Q_OBJECT
public:
ClientHandler( QTcpSocket *socket ) : _socket( socket )
{
connect( _socket, SIGNAL( disconnected() ), this, SLOT( disconnected() ) );
connect( _socket, SIGNAL( readyRead() ), this, SLOT( readyRead() ) );
// ...
}
private slots:
// this method will be invoked when client disconnects
void disconnected()
{
// ...
deleteLater(); // delete ClientHandler instance
}
// this will be invoked when client sends some data (remember that you receive a stream of bytes )
void readyRead()
{
_buffer.append( _socket->readAll() );
// while there is at least one complete message in the buffer:
// parse & process the message
// remove that message from the buffer
}
private:
QTcpSocket *_socket;
QByteArray _buffer;
};
// ...
void mythread::processConnection()
{
QTcpSocket *clientConnection = tcpServ->nextPendingConnection();
if( clientConnection != 0 ) {
new ClientHandler( clientConnection );
}
}
To copy to clipboard, switch view to plain text mode
You can also derive ClientHandler from QThread and use the blocking interface (just like in threaded fortune server example).
Bookmarks