PDA

View Full Version : QTcpServer



DmitryNik
30th September 2011, 17:59
Hello!

I would like to create a kind of chat with a help of classes QTcpServer and QTcpSocket. But probably I'm missimg something definitely important. So, my idea is to re-implement the QTcpServer::incomingConnection method, get the socket's descriptor and the socket itself, put it in QMap<int, QTcpSocket>. And when the signal readyRead() will be emited, start to search in a dictionary the client's socket by key's value. But here is the main problem: how we can get that value? Yes, we can use this->socketDescriptor() method, but it will return only the server descriptor, not the client's descriptor. I need some hint. In which way I need to move? And how I can get the client's socket descriptor, which is sending the signal at any one time?

For reading I'm using the standart QTcpSocket method: readAll(): qDebug() << this->currentSocket->readAll().data();

Is my approach wrong?

Thank you beforehand for answers.


ADDED:

this->currentSocket->socketDescriptor() will return only the latest connected socket's descriptor... And that is the problem. Yes, I can get the readyRead() signal. But I can't get any descriptors, which belong to the client that sent a data-packet. I need to keep each channel open until client will disconnect.

Added after 52 minutes:

I figured it out by myself=)) So, I still can use the magic line: QTcpSocket *currentSocket = (QTcpSocket *)this->sender();
In this case I receive the object which sent the readyRead() - signal. In my humble opinion this one is solution.
Question for guru: is it only approach? Or I missed something once again? =)

wysota
1st October 2011, 01:04
In my opinion the best approach is to use proper encapsulation. If you have a class for handling client connections, you'll end up with a situation where one socket is bound with exactly one instance of the connection class. Therefore you immediately know which client you are handling because each handler object only deals with one socket.


class Handler : public QObject {
Q_OBJECT
public:
Handler(QTcpSocket *clientSocket, QObject *parent = 0) : QObject(parent), sock(clientSocket) {
connect(sock, SIGNAL(readyRead()), this, SLOT(handleInput()));
}
private slots:
void handleInput() {
QByteArray data = sock->readAll();
doStuffWith(data);
}
private:
QTcpSocket *sock;
};

DmitryNik
1st October 2011, 08:07
Thank you!
That's what I missed.