开发者

I'm trying to make server/client but I don't know how to connect signals and slots

I'm trying to make server/client in Qt.

TCP Server takes maximum 4 connections from client.

To create...

// server.h
class Server : public QTcpServer{
    ...
    QList<QTcpSocket *> list;
}

// server.cpp
Server::start(){
    QTcpSocket *curr = nextPendingConnection();
    connect(curr, SIGNAL(disconnected()), curr, SLOT(deleteLater()));
    list.append(curr);
}

This开发者_JAVA百科 code would delete the memory by connecting disconnected() signal to deleteLater() but I don't know how to remove the pointer from list. How can I know which connection is closed?

I want to remove disconnected QTcpSocket pointer element from list to manage connections.

please help...

(I think if there was a SIGNAL(disconnected(QTcpSocket *)), this must be so much easier)


Like others pointed out qobject::sender should work

Server::start(){
    QTcpSocket *curr = nextPendingConnection();
    connect(curr, SIGNAL(disconnected()), curr, SLOT(deleteLater()));
    connect(curr, SIGNAL(disconnected()), this, SLOT(onDisconection()));
    list.append(curr);
}

void onDisconection()
{
  list.removeOne(qobject_cast<QTcpSocket*>(sender()));
}

but as said sender has some drawbacks and I suggest using a signal mapper see http://doc.qt.io/qt-5/qsignalmapper.html


You could use QObject::sender():

void onDisconnect()
{
    QTcpSocket sock = qobject_cast<QTcpSocket*>(sender());

    if (sock != 0)
    {
        list.removeAll(sock);
        sock->deleteLater();
    }
}

Just connect this slot to the disconnected() signal and the memory will be freed and the socket removed from the list.

Using sender() has some drawbacks, though. I suggest reading the docs before using it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜