qt网络事件之QSocketNotifier

简介

QSocketNotifier用于处理网络事件的,即事件处理器

结构

QSocketNotifier +qintptr socket() +Type type() +bool isEnabled() +void setEnabled(bool) +void activated(int socket, QPrivateSignal) #bool event(QEvent *) QSocketNotifierPrivate +qintptr sockfd +QSocketNotifier::Type sntype +bool snenabled

qintptr socket():表示对应的网络套接字

Type type():表示关注的事件类型,使用枚举表示

cpp 复制代码
enum Type { Read, Write, Exception }

bool isEnabled():表示对应的是否注册到事件分发顺器中

void setEnabled(bool):是槽函数,表示是否将套接字注册到事件分发器中

cpp 复制代码
void QSocketNotifier::setEnabled(bool enable)
{
    Q_D(QSocketNotifier);
    if (d->sockfd < 0)
        return;
    if (d->snenabled == enable)                        
        return;
    d->snenabled = enable;

    if (!d->threadData->hasEventDispatcher())
        return;
    if (Q_UNLIKELY(thread() != QThread::currentThread())) {
        return;
    }
    if (d->snenabled)
        d->threadData->eventDispatcher.loadRelaxed()->registerSocketNotifier(this);
    else
        d->threadData->eventDispatcher.loadRelaxed()->unregisterSocketNotifier(this);
}

void activated(int socket, QPrivateSignal):信号,在event事件处理函数中,如果事件类型为QEvent::SockAct或者QEvent::SockClose,会触发该信号

bool event(QEvent *):事件处理函数

cpp 复制代码
bool QSocketNotifier::event(QEvent *e)
{
    Q_D(QSocketNotifier);
    // Emits the activated() signal when a QEvent::SockAct or QEvent::SockClose is
    // received.
    if (e->type() == QEvent::ThreadChange) {
        if (d->snenabled) {
            QMetaObject::invokeMethod(this, "setEnabled", Qt::QueuedConnection,
                                      Q_ARG(bool, d->snenabled));
            setEnabled(false);
        }
    }
    QObject::event(e);                        // will activate filters
    if ((e->type() == QEvent::SockAct) || (e->type() == QEvent::SockClose)) {
        emit activated(d->sockfd, QPrivateSignal());
        return true;
    }
    return false;
}

触发网络事件

QEventDispatcherUNIX QEventDispatcherUNIXPrivate QSocketNotifier processEvents qt_safe_poll activateSocketNotifiers event emit activated QEventDispatcherUNIX QEventDispatcherUNIXPrivate QSocketNotifier

相关推荐
西红市杰出青年4 分钟前
MCP 的三种数据传输模式教程(stdio / SSE / Streamable HTTP)
网络·网络协议·http·ai
Filotimo_11 分钟前
内网穿透概念
网络
minji...1 小时前
Linux 进程间通信(三)命名管道
linux·服务器·网络
kongba0072 小时前
OpenClaw v2026.3.23 安全配置复盘:从多处明文到集中受控存储《OpenClaw 安全部署 SOP(v2026.3.23)V2》
服务器·网络·安全
机器视觉知识推荐、就业指导3 小时前
LVGL真能动摇Qt的地位吗?
开发语言·qt·系统架构
郭涤生3 小时前
CANopen 基础复习
服务器·网络·c++
normanhere3 小时前
H3C无线调优案例
网络
饿了吃洗衣凝珠4 小时前
hcip 作业
网络
C++ 老炮儿的技术栈4 小时前
两个线程对socket 进行读和写,需要加锁吗
java·服务器·网络
陌上花开缓缓归以5 小时前
linux boot 烧写纪要以及内存相关分析
linux·服务器·网络