这是两个小脚本,显示我现在如何使用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并重新添加它?
答案 0 :(得分:0)
我在经过一些实验后发现,一旦触发套接字关闭,就会导致kq.control立即返回,并在返回事件的flags属性中设置KQ_EV_EOF
。我只需要在每次返回事件时检查标志,以确保它没有设置KV_EQ_EOF
!