Change peerName in a TCP client/server connection



  • Good morning to all.
    I'm working on a job that establish a TCP connection between a server and some clients.
    The clients are some DTUs, and their firmware is provided from the seller.
    When I lauch the server, the connection is set correctly. When I search for peerName, peerAddress and peerPort I have an undefined value for peerName.
    So, I'm trying to change the peer name using protected function QAbstractSocket::setPeerName(QString), as in this snippet:

    // snippet code
    QtcpServer* tcpServer = new QTcpServer;
    QTcpSocket* tmp = new QTcpSocket;

    tmp = tcpServer->nextPendingConnection();
    QString aa = tmp->peerAddress().toString();
    QString bb = tmp->peerName();
    QString cc = QString::number(tmp->peerPort());
    
    QMessageBox::warning(this, "New client: ", bb + "* - "+ aa + ":" + cc);
    

    Here bb is an empty string. So, I called the following method:

     tmp->setPeerName("NewClient01");
    

    The compiler give me this error:

    error: ‘void QAbstractSocket::setPeerName(const QString&)’ is protected within this context

    How can I solve my problem?
    More, can I change the peer name from server side, or I can do it only from client side?

    Thanks to all can help me.



  • @glafauci61 said in Change peerName in a TCP client/server connection:

    So if you really want to call a protected method in C++ you must write the code in your own class which is derived from the base class. That's what protected means. In itself this has nothing to do with Qt.

    You are delivering the socket you wish to call setPeerName() on from http://doc.qt.io/qt-5/qtcpserver.html#nextPendingConnection. So you would need to write your own class derived from QTcpServer which at minimum returned its own value for QTcpSocket, which in turn you would need to derive from you own class for this derived from QTcpSocket. So I make it you would need two derived classes of your own, one from QTcpServer and another from QTcpSocket...

    Whether this is the right approach is another matter. It is "somewhat unusual" to need to derive in order to call a protected function (i.e. you "usually" should not find you are wanting to override a protected function), but this varies according to your usage....



  • @JonB
    Thanks for your answer, it was very useful.
    Only for comment, I understand that peerName and others 'peer' members aren't needful for my application, so a don't care of them.
    I understand (I don't know if it is right) that these class members will be used when I need to establish a peer-to-peer connection, that isn't my goal.
    Thank you


Log in to reply
 

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