让gevent在一个套接字成功时停止轮询

时间:2016-03-18 03:43:39

标签: python gevent

我使用gevent轮询几个套接字只是为了查看其中一个指定的端口是否打开。如果其中一个套接字成功,如何使gevent停止轮询?

import gevent
from gevent import socket

vm_ip = "10.3.12.2"
ports = [22, 16120, 16122]
def fn(port):
    while True:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(5)
        result = s.connect_ex((vm_ip, port))
        s.close()
        if result == 0:
            return

jobs = [gevent.spawn(fn, port) for port in ports]
gevent.joinall(jobs, timeout=30)

1 个答案:

答案 0 :(得分:0)

您可以在while循环中设置一个标志,并在找到结果时关闭该标志。 Greenlets是协程,而不是线程,所以这样做没问题:

import gevent
from gevent import monkey
monkey.patch_all()
from gevent import socket

vm_ip = "10.3.12.2"
ports = [22, 16120, 16122]
found = False
def fn(port):
    while not found:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(5)
        result = s.connect_ex((vm_ip, port))
        s.close()
        if result == 0:
            found = True
            return

jobs = [gevent.spawn(fn, port) for port in ports]
gevent.joinall(jobs, timeout=30)