1

这里有两个小脚本,展示了我现在如何使用 kevents,并重现了我的问题。

kqtest.py:

import socket
import select
import threading

server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
server_sock.bind(('localhost', 8080))
server_sock.listen(1)

client, addr = server_sock.accept()

kev = select.kevent(client)
kq = select.kqueue()
kq.control([kev], 0, 0)

while True:
    events = kq.control([], 1, 1)
    if events:
        event = events[0]
        if event.ident == kev.ident:
            print("ready to read client %s:%s" % addr)
            print(client.recv(1024))

kqtesttrigger.py

import socket

trigger = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
trigger.connect(('localhost', 8080))
trigger.send(b"THIS IS THE TRIGGER!!! LA-DEE-DAAAAA-DEE-DAAA!!!")

触发后 kqtest 的输出:

ready to read client 127.0.0.1:63868
b'THIS IS THE TRIGGER!!! LA-DEE-DAAAAA-DEE-DAAA!!!'
ready to read client 127.0.0.1:63868
b''
ready to read client 127.0.0.1:63868
b''
ready to read client 127.0.0.1:63868
b''
...this repeats until I kill it

我想要的是仅在将数据添加到套接字时才触发 kevent。我是否需要从 kqueue 中删除 kevent 并重新添加它?

4

1 回答 1

0

我经过一些实验发现,一旦触发套接字关闭,它会导致 kq.control 立即返回,并KQ_EV_EOF在返回事件的 flags 属性中进行了设置。我只需要在每次返回事件时检查标志以确保它没有KV_EQ_EOF设置!

于 2014-02-06T19:14:18.417 回答