Solved Connecting and reading data from multiple QTcpSockets with QTcpServer
-
Hello! I recently began working with QTcpSocket and QTcpServer, I am where I have a server which will accept all the oncoming clients / tcpsockets. It works great and all, however I have hit into a difficult dilemma.
Every new connection I will take the pending connection and insert it into a vector as well as set up connections so I can communicate with the client. (Save the clients socket in a vector)
QTcpSocket *newConnection{m_Server->nextPendingConnection()}; //QList<QTcpSocket*> m_PendingC.append(newConnection); //Connection for when the client disconnects from the server connect(newConnection, &QTcpSocket::disconnected, this, &MyServer::disconnected); //Connection for when the client sends data to the server connect(newConnection, &QTcpSocket::readyRead, this, &MyServer::reading); ... void MyServer::reading(){ qDebug() << "Data from the client is :" << /*reference to the client*/.readAll(); }
However, the problem occurs when I receive data from the client, I don't know of any way to check which client sent the information and going through the list of clients and checking by saying
.readAll()
seems to be inefficient.Is there any method or signal I can use that will return a reference / pointer to the socket who sent the data to the server?
-
@cdecde57 in the slot typecast the this->sender() to socket type.
-
@cdecde57 in the slot typecast the this->sender() to socket type.
-
Thank you for your help, Worked like a charm! I guess just understanding what Qt provides makes things a lot easier, lol.
Also sorry for the late response, I had to finish another task which took my time away from programming.
Anyways, if anyone wants to see what I did based off of @nagesh s feedback I provide it down below just for the sake of it.
I used a lambada function as the slot and used the sender() function in the this pointer to capture the specific socket making the call and from there I was able to send it to the appropriate function. I know that you can make function calls with SLOT(myFunciton(params)) etc, but I couldn't get the signal to work and decided to just go the easy way with lambada, but the main idea is that by using the sender function you can obtain the object who triggered the signal to start with.
connect(newConnection, &QTcpSocket::readyRead, this, [=](){ reading(static_cast<QTcpSocket*>(this->sender())); });
-
@cdecde57 There is no need for sender(). You're already using a lambda as slot, so simply capture the sender:
connect(newConnection, &QTcpSocket::readyRead, this, [newConnection, this](){ reading(newConnection); });