PDA

View Full Version : Handle more than one QTcpSockets with one QTcpServer. How?



jackmack
22nd July 2010, 09:12
Hi all,

some background information:
I have a simple application with running a server. Several other apps should be able to connect as client to it.

Now I'm using QTcpServer. After call listen() the server is able to accept incoming clients.
I have connected the newConnection() signal to a private slot clientConnected(). According as the docs I call within nextPendingConnection() to get an instance of QTcpSocket. Then I connect the signal disconnected() to slot deleteLater() of that instance.

If several clients connects to the server there are several QTcpSocket instances. I store the reference of instances to a list because the server should send data to all connected clients.

Now the problem:
If one client aborts the connection how I can remove the reference of that QTcpSocket instance from my list?
The disconnect() signal is handled within the scope of QTcpSocket. I should have a method like QTcpServer::connectionAborted(QTcpSocket* client).

Have anybody an idea?

Thanks, Jack

tbscope
22nd July 2010, 09:57
I assume you mean "aborts the connection" is the same as closing the connection (or disconnecting)?

If so, don't connect the QTcpSocket::disconnected() signal to the deleteLater() slot. Instead create a connectionAborted() slot and link it the disconnected() signal to this slot.
In the connectionAborted slot remove the item from your list and delete the socket using deleteLater() for example

jackmack
22nd July 2010, 13:45
Hi,

create an own slot connectionAborted() is nice. But how can I find out inside that method which QTcpSocket instance has called him?

Connecting QTcpSocket::disconnected() to MyServer::connectionAborted() means that all QTcpSocket instances calls the same method.

Which one I should remove?

But I see one chance: In connectionAborted() I can check what QTcpSocket instance has state != SocketState::ConnectedState, then call deleteLater() and remove it from list.

I try it. Thanks.

tbscope
22nd July 2010, 14:55
Use sender() and cast it to a QTcpSocket

Some people don't like this and use a signal mapper.

Edit: See also here:
http://www.qtcentre.org/wiki/index.php?title=Server_with_multiple_clients_witho ut_threads

jackmack
22nd July 2010, 16:49
Thanks. The wiki link is great.

I think it's nicer to clean the client list with identify the instance by sender().

And: It's long time ago I worked with Qt. I didn't know the sender() method.
But I like it instead of MFC. :)