正常关闭QTcpsocket

本文探讨了在Qt应用中通过合理利用信号槽机制实现QtTcpSocket客户端连接断开时自动释放资源,避免内存泄漏的问题。通过实例演示了如何在连接建立后设置断开连接信号的槽函数来调用deleteLater()方法,确保资源在数据发送完成后被正确释放。
myClient->disconnectFromHost();
Qt的例子里面有这段话:
which will close the connection after QTcpSocket has finished writing the fortune to the network. Because QTcpSocket works asynchronously, the data will be written after this function returns, and control goes back to Qt's event loop. The socket will then close。
也就是说,和服务器连接的断开会在发送完数据之后进行。
如果我们加了这样一个槽函数:
connect(myClient, SIGNAL(disconnected()),myClient, SLOT(deleteLater()));

就能够避免出现内存泄漏。



 QTcpSocket *myClient=tcpServer->nextPendingConnection();

    //我们获取已经建立的连接的子套接字

   connect(myClient,SIGNAL(disconnected()),myClient,SLOT(deleteLater()));

   myClient->write(block);

   myClient->disconnectFromHost();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值