serverFind.py 1.8 KB

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