serverFind.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import requests
  2. import time
  3. import random
  4. from concurrent.futures import ThreadPoolExecutor
  5. from .ipFind import ipFind # 假设ipFind是一个从本地模块导入的函数
  6. def task(i):
  7. """发送HTTP请求检查服务器状态的任务函数"""
  8. sleep_seconds = random.randint(1, 3)
  9. # 可选:取消注释以显示线程执行信息
  10. # print('线程名称:{},参数:{},睡眠时间:{}'.format(threading.current_thread().name, i, sleep_seconds))
  11. try:
  12. # 随机延迟,减少请求风暴
  13. time.sleep(sleep_seconds)
  14. # 发送请求并设置合理的超时时间
  15. r = requests.get(f'http://{i}:7162/findserver', timeout=3).text
  16. except requests.exceptions.ConnectTimeout:
  17. # 连接超时处理
  18. r = '0'
  19. except requests.exceptions.ReadTimeout:
  20. # 读取超时处理
  21. r = '0'
  22. except requests.exceptions.ConnectionError:
  23. # 连接错误处理
  24. r = '0'
  25. except Exception as e:
  26. # 其他异常处理
  27. print(f"请求处理异常: {e}")
  28. r = '0'
  29. return [i, r]
  30. def findServer():
  31. """查找可用服务器的主函数"""
  32. time1 = time.time()
  33. # 创建线程池,设置合理的最大工作线程数
  34. with ThreadPoolExecutor(max_workers=500) as pool:
  35. # 获取所有IP地址
  36. allIP = ipFind()
  37. # 使用线程池并行执行任务
  38. result = list(pool.map(task, allIP))
  39. print(f'耗时:{time.time() - time1}')
  40. # 筛选可用服务器
  41. serverList = []
  42. for item in result:
  43. if "天府综合平台一期:" in item[1]:
  44. item[1] = item[1].replace("天府综合平台一期:", "")
  45. serverList.append(item)
  46. return serverList
  47. if __name__ == '__main__':
  48. l = findServer()
  49. print("可用服务器列表:", l)