服务器第一次开启(RUN)的时候,客户端端连接上来是没有问题的。然后我关闭(STOP)服务器,再开启,客户端连接上来,就会程序异常。
我在处理有新连接的信号的槽函数里(即v_SlotConnection)做了打印,当第二次开启服务器,客户端连接上会两次进入v_SlotConnection,然后就程序异常了。bug解决了,是因为我把newConnection放在开始的按钮里,放出来就没问题了,原因不明白。
//开始运行tcp服务端
if((ui->buttonrun->text())=="RUN")
{
qDebug()<<"RUN";
//监听网卡下所有8087
if(false == tcpServer->isListening())
{
tcpServer->listen(QHostAddress::Any, 8087);
}
//监听固定ip下 8087
// tcpServer->listen(QHostAddress(ipAddr), serverPort);
ui->buttonrun->setText("STOP");
}
else
if((ui->buttonrun->text())=="STOP")
{
qDebug()<<"stop";
ui->linkNumber->display(0);
ui->buttonrun->setText("RUN");
//主动和客户端端口断开
if(NULL == tcpSocket)
{
//清空计数
tcpServer->close();
}
else
{
//倒着断开加入链表的ip地址
int i=clients.length()-1;
qDebug()<<i<<"clients.length()"<<clients.length();
while(i>=0)
{
clients.at(i)->disconnectFromHost();
i--;
}
tcpServer->close();
}
}
connect(tcpServer, &QTcpServer::newConnection, this, &ServerWidget::v_SlotConnection);