QT server服务端如何判断客户端断开连接

在QT编程中有时会用到server服务端与客户端进行TCP网络通信,服务端部分代码如下:

1、创建server用于监听客户端套接字

this->server = new QTcpServer(this);
this->server->listen(QHostAddress::Any,5001);
connect(this->server,SIGNAL(newConnection()),this,SLOT(newConnection()));

2、newConnection()函数

//信号槽函数--新的设备连接
void Widget::newConnection()
{
    //查询空闲的套接字
    for(int i = 0; i<SOCKET_MAXNUM; i++)
    {
        if(!this->socketFlag[i])
        {
            this->socketIndex = i;
            break;
        }
    }
    this->socket[socketIndex] = this->server->nextPendingConnection();
    this->socketFlag[socketIndex] = SOCKET_FLAG_CONNECTED;
    connect(this->socket[socketIndex],SIGNAL(readyRead()),this,SLOT(readData()));
    scan_Device();
}

3、update_DeviceNetState()函数用于检测更新socket状态

//更新设备连接状态,清理释放过期的SOCKET
void Widget::update_DeviceNetState()
{
    int onlineDeviceNum = getChildItemCount(DEVICE_TB_ONLINE_DEVICE);
    qDebug()<<"Line-658 当前在线设备数量:"<<onlineDeviceNum;
    for(int i = 0;i<onlineDeviceNum;i++)
    {
        int socketID  = ui->DEVICE_TABLE->topLevelItem(DEVICE_TB_ONLINE_DEVICE)->child(i)->data(3,Qt::SocketIndex).toInt();
        bool netState = send_WakeHand(socket[socketID]);
        qDebug()<<"此设备在线? "<<netState;
        if(netState == STATE_OFFLINE)
        {
            clearSocket(socketID);
            deviceNetStateChange(i,DEVICE_TB_OFFLINE_DEVICE,DEVICE_TB_ONLINE_DEVICE,-1);
        }
    }
}

4、send_WakeHand(QTcpSocket *currSocket) 发送握手信号返回套接字返回值

//发送握手信号,判断设备是否掉线
bool Widget::send_WakeHand(QTcpSocket *currSocket)
{
    int ret = currSocket->write("wake hands");
    qDebug()<<"ret ="<<ret;
    if(ret == -1)
        return STATE_OFFLINE;
    return STATE_ONLINE;
}

5、利用定时器QTimer定时检查更新套接字状态

QTimer *timer = new QTimer(this);
//定时检查更新设备的网络状态    
connect(timer,SIGNAL(timeout()),this,SLOT(update_DeviceNetState()));
timer->start(1000);

代码仅供学习参考,未经允许,禁止转载

 

posted @ 2017-08-18 17:27  下个季节的风  阅读(7898)  评论(1编辑  收藏  举报