how readyread() know about from which socket ,it is called



  • If i have connected multiple client to server,In that case how readyread() signal know which socket called it.
    connect(socket,SIGNAL(readyRead()),this,SLOT(Read()),Qt::DirectConnection);
    if i write qDebug()<<socketDescriptor in Read() SLOT,it gives particular socketDescriptor of the socket connected to it.so my question is how Read() will know about that socketDescriptor value.



  • Hi,

    In your "Read()" slot, you can retrieve the QTcpSocket by using sender().

    void MyClass::Read() //Read slot
    {
        QTcpSocket * socket = static_cast<QTcpSocket *>(sender());
        if(!socket)
             return; //Problem to retrieve the socket, ususally should not happen.
    
        QByteArray data = socket->readAll();
        //...
    }
    


  • @Gojir4 thanks. if we dont use sender() syntax.it can also be possible by doing..
    QByteArray data1= socket->readAll();
    In this socket is initialize in header file and the declared it in run() of thread class
    like this:
    socket=new QTcpSocket();

    if(!socket->setSocketDescriptor(this->socketDesc))
    {
        emit error(socket->error());
        return;
    }
    connect(socket,SIGNAL(readyRead()),this,SLOT(Read()),Qt::DirectConnection);
    

    so my question is in code below:
    void MyThread::Read()
    {
    qDebug()<<"socket in Read:"<<s;
    QByteArray data1= socket->readAll();//{qDebug()<<"Message received ";}
    qDebug()<<socketDescriptor<<"Data is here"<<data1;
    }

    how Read function know about particular socketDescriptor of socket if we have multiple client connected .Because in that situation there are more than one socket are connected. (socketDescriptor is initialized in header file)



  • @JadeN001
    Given a QTcpSocket, from http://doc.qt.io/qt-5/qabstractsocket.html there are methods like localAddress/Port() & peerAddress/Name/Port() to see what the socket is connected to at server/client sides.

    Otherwise, from the "native socket descriptor" passed to socket->setSocketDescriptor(this->socketDesc), I assume this is the native "SOCKET" type you can access the struct sockaddr_in to get this information.



  • @Gojir4
    QTcpSocket * socket = static_cast<QTcpSocket *>(sender());
    its not working, it stops my server and returns socket value as QObject(0X0). what could be the issue here?


  • Moderators

    Just create a worker instance per connection so you can handle the incoming data separately and know every time where the data is coming from.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.