tcpserver检测断开qt_QTcpServer或QTcpClient(在服务器端)知道,已连接的客户端现已断开连接...

这个代码示例展示了如何在QTcpServer中使用QSignalMapper来跟踪和处理客户端的断开连接事件。当新的连接到来时,服务器创建一个新的客户端套接字,并将其映射到信号映射器上。当客户端断开连接时,信号映射器将发出信号,传入断开连接的套接字对象,以便进行清理和更新表格视图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

您在incomingConnection(int)内创建的套接字具有disconnected()信号。使用QSignalMapper确定断开连接的套接字并更新表视图。快速而脏的代码,可能很有帮助,当然还有很多语法错误:

TcpServer::TcpServer(QWidget *parent) :

QDialog(parent),

ui(new Ui::TcpServer)

{

ui->setupUi(this);

m_coisSerSo = new CoisServerSocket(this);

count = 0;

// The mapper forwards the signal from the client socket,

// adding the socket itself as an argument.

this->mapper = new QSignalMapper(this);

connect(this->mapper, SIGNAL(mapped(QObject*)),

this, SLOT(clientDisconnected(QObject*)));

connect(m_coisSerSo,SIGNAL(newConnection()),this, SLOT(updateConnectionTable()));

}

void CoisServerSocket::incomingConnection(int socketId)

{

socketClient = new CoisClientSocket(this);

socketClient->setSocketDescriptor(socketId);

// Map the socket so that we can receive its disconnection

// notification. When the socket emits the "disconnected()"

// signal, the mapper will emit "mapped(QObject*)" and will

// pass the socket as the argument.

this->mapper->setMapping(socketClient, socketClient);

connect(socketClient, SIGNAL(disconnected()), this->mapper, SLOT(map()));

peerAdd = socketClient->peerAddress().toString();

}

void CoisServerSocket::clientDisconnected(QObject* object)

{

if (CoisClientSocket* client = qobject_cast(object))

{

// Unmap the socket.

this->mapper->removeMappings(client);

// Handle disconnection here.

...

// A consequence of mixing a TCP server and a dialog in the

// same class is that passing "this" as an argument to the

// socket constructor doesn't help much with memory management.

// They will stay around as long as the dialog lives. Delete

// them once they aren't needed anymore.

client->deleteLater();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值