#-*-coding:utf-8 -*-
'''
问题:
1,pycurlmulti如何在运行中检测到出现故障的请求?
a) m.perform 返回的正确数小于加入的句柄数
b) m.info_read 读取发生故障的句柄及原因(注意只能给读取一次)
c) 移除句柄,然后重新添加。
'''
import time
import threading
from functools import partial
import traceback
import pycurl
from io import BytesIO
MAX_CONNCETION_NUM = 500
index2count= {}
#避免运行时增加
for index in range(MAX_CONNCETION_NUM):
index2count[index] = 0
def period_check():
while True:
now = time.time()
count =0
for k,v in index2count.items():
print (k,v)
count += v
print ("---------------",count)
time.sleep(10)
def dealer_data( buffer,index ):
index2count[index] +=1
def get_one_curl( url,index):
#lc_data = threading.local()
c = pycurl.Curl()
c.setopt(c.NOSIGNAL, 1) #解决抛出SegmentFault的问题,
# 2 设置选项
c.setopt(c.WRITEFUNCTION, partial(dealer_data,index=index ) )
#STR;BRUX0;Brussels;RTCM 3.0;1004(1),1006(10),1008(10),1012(1);2;GPS+GLO;IGS;BEL;50.47;4.21;0;0;SEPT POLARX4TR;none;B;N;1300;ROB
c.setopt(c.URL, url )
c.setopt(pycurl.USERPWD,"user:passwd")
#c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0 )
c.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
c.setopt(pycurl.HTTPHEADER, ("Ntrip-Version: Ntrip/2.0",'User-Agent: NTRIP ExampleClient/2.0'))#此处为必须!
return c
def build_pycurlmulti( dest_url, connection_num ):
'''
短时间内发起大量连接会被拒绝
'''
m = pycurl.CurlMulti()
curls =[]
for index in range(connection_num):
c = get_one_curl( dest_url, index )
curls.append(c)
m.add_handle( c )
#ret, num_handles = m.perform()
#time.sleep(0.1) #每隔1秒添加一个句柄,防止大量并发连接请求被服务器拒绝。
while 1:
ret = m.select(1.0)
if ret == -1: continue
while 1:
ret, num_handles = m.perform()
if connection_num != num_handles:
error_info = m.info_read()[2]
for curl_obj, error_num,error_str in error_info:
#7 Failed to connect to fastgis.cn port 5000: Timed out
#56 Recv failure: Connection was reset
if error_num in (7,56):
m.remove_handle(curl_obj)
m.add_handle(curl_obj)
if ret != pycurl.E_CALL_MULTI_PERFORM:
break
'''
Ntrip-Version: Ntrip/2.0<CR><LF>
User-Agent: NTRIP ExampleClient/2.0<CR><LF>
'''
import threading
threads = []
# 1,看门狗,状态检测线程
threads.append( threading.Thread(target=period_check, args=() ) )
# 2,
host="http://fastgis.cn:5000/file"
threads.append( threading.Thread(target=partial(build_pycurlmulti , dest_url=host, connection_num= MAX_CONNCETION_NUM ) ) )
for t in threads:
t.start()
for t in threads:
t.join()
pass
转载于:https://my.oschina.net/cppblog/blog/671857