在Python27Scripts的cmd下安装:easy_install poster-0.8.1-py2.7.egg
文件1:PostFile.py
#!/usr/bin/python # -*- coding: UTF-8 -*- from poster.encode import multipart_encode from poster.streaminghttp import register_openers import urllib2 def post_file(name, filename): try: # 在 urllib2 上注册 http 流处理句柄 register_openers() # headers 包含必须的 Content-Type 和 Content-Length # datagen 是一个生成器对象,返回编码过后的参数 fo = open(filename, "rb") datagen, headers = multipart_encode({name: fo}) # 创建请求对象 request = urllib2.Request("http://192.168.86.111:8008/tcs/", datagen, headers) #request = urllib2.Request("http://192.168.56.101:8008/tcs/", datagen, headers) # 实际执行请求并取得返回 reply = urllib2.urlopen(request).read() except Exception, e:return "" else: return reply finally: fo.close() #post_file("wav1", "test.wav")
文件2:TCSServerTest.py
#!/usr/bin/python # -*- coding: UTF-8 -*- import threading import time from PostFile import post_file exitFlag = 0 totalErrorCnt = 0 totalCount = 0 class myThread(threading.Thread): # 继承父类threading.Thread def __init__(self, threadID, threadName): threading.Thread.__init__(self) self.threadID = threadID self.threadName = threadName def run(self): # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 print "Starting " + self.threadName + str(self.threadID) while not exitFlag: t_beging = time.clock() result = post_file(self.threadName, "test.wav") t_end = time.clock() dt = t_end - t_beging threadLock.acquire() global totalCount totalCount += 1 dt_wall = time.time() - totalWallTime #print result if result == "": global totalErrorCnt totalErrorCnt += 1 print "%s %s%d -> %d / %d = %f ... %d" % (time.ctime(time.time()), self.threadName, self.threadID, dt_wall, totalCount, dt_wall/totalCount, totalErrorCnt) threadLock.release() time.sleep(0.001) print "Exiting " + self.threadName + str(self.threadID) threadLock = threading.Lock() threads = [] global totalWallTime totalWallTime = time.time() for i in range(1, 6): # 创建新线程 thread1 = myThread(2*i-1, "Thread") thread2 = myThread(2*i, "Thread") # 开启线程 thread1.start() thread2.start() # 添加线程到线程列表 threads.append(thread1) threads.append(thread2) while True: a = raw_input() if a == 'q': exitFlag = True break for t in threads: t.join() print "Process Exiting"
涉猎不深,初编,后不断改进……