Recently in the use of Qtnetwork Programming server program for TCP/IP communication, the general process is as follows:
1. Create a Qtcpserver instance to listen to the target IP and port;
2. Once the supervisor hears there is a connection between the access and the client socket;
3. Use the socket for communication;
4. After the communication is over, the socket can be released manually, or it can be released automatically when releasing the Qtcpserver.
At the time of writing, I did the following things:
Tcpnetwork::tcpnetwork () { ... Connect (Mysocket, SIGNAL (Disconnect (qtcpsocket*)), this, SLOT (Serverconnectionlost (qtcpsocket*))); ...}
Tcpnetwork::~tcpnetwork () { if (tcpserver! = NULL) { delete tcpserver; }}
<pre name= "code" class= "CPP" >void tcpnetwork::serverconnectionlost (Qtcpsocket *socket) { if (socket = = Mysocket) { ... Debug Delete mysocket; Mysocket = NULL; ... }}
This will cause crashes when closing the program window, and after looking at the source code of the Qtcpserver destructor, it is found that QT will first check if the socket pointer under Qtcpserver has been released, and then perform the close operation of each socket. Then release the unused socket memory that was just checked, and finally release Qtcpserver.
If the Qtcpsocket::d isconnect () signal is connected to a slot with a release socket operation, then if the socket is not closed, the qtcpserver is directly destructor, When you execute the disconnect socket (if you have previously disconnected and no longer perform this step), the slot with the delete socket operation is triggered, but the destructor does not know, and then the destructor releases the socket, causing the memory of the socket to be repeatedly released, causing the crash.
WORKAROUND: Close the socket before closing the window so that the operation to close the socket is no longer performed in the destructor. Or, do not add slots that contain the release socket operation when the connection is disconnected.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
One need to be aware of the release of Qsocket