views:

50

answers:

2

Hello, 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 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)

A: 

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.

Job
Never delete an object if you are in a slot connected synchronously to the object. The code in QTcpSocket might continue doing stuff after emitting disconnected(), and then crash, as "this" is already deleted. Better use deleteLater().
Frank
@Frank: Good point, I corrected my answer.
Job
A: 

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.nokia.com/latest/qsignalmapper.html

Olorin
Thanks for your extra information about signal mapper. This is what I was looking for..
your welcome :D
Olorin