Python 实现通过服务器接口做多线程并发测试

每秒启动一线程,待 50 个线程都启动后,并发向服务器接口以特定的 HTTP 包协议发送消息,核查 HTTP 的响应状态以及响应时间。

#!/usr/bin/env python
#coding=utf8

import httplib, urllib,time,datetime
import thread
#outFile= open("/home/zhouxiaoli/output/MD_Login_2.txt","w")
outFile= open("D:\\MD_Login_2.txt","w")
def upload(no,interval):     
    httpClient = None
    params = urllib.urlencode({'feel':'2','content': 'zhouxiaoli123','hidden':'0','disid':'2'})
    headers = {"Content-type": "application/x-www-form-urlencoded"
                    , "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
                    ,"Cookie": "PHPSESSID=pmau7lj2vmbu1mf7ef0hkp46k0; docdocuid=10088; dochead=Uploads%2FChat%2F2015-05-26%2Fa835acf71b39dedf646204d654f04bd6_thumb.jpg; think_language=zh-CN"
                    ,"User-Agent": "Mozilla/5.0 (Linux; Android 4.4.2; HUAWEI MT7-UL00 Build/HuaweiMT7-UL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36"}

    print "the Thread sleep  %d sec\n" %(50-no)
    time.sleep(50-no) 
    httpClient = httplib.HTTPConnection("app1.qshealthcare.com", 80, timeout=30)
    httpClient.request("POST", "/doctor.php?m=Doctor&c=weibo&a=addweibo", params, headers)
    #需要记录当前时间
    begin = datetime.datetime.now()
    print begin
    response = httpClient.getresponse()
    #需要记录响应时间
    end =  datetime.datetime.now()
    print "the Thread sleep  %s sec\n" %(end-begin)
    outFile.write(str(end-begin)+',')
    print response.status
    outFile.write(str(response.status)+'\n')
    print response.reason
    print response.read()
    #print response.getheaders
    while 1: 
        time.sleep(1)  
def test():
     i=0
     while 1:
          i+=1
          if i < 50:
             thread.start_new_thread(upload,(i,i,))
          else:
             i=0
             time.sleep(3)
          time.sleep(1)

test()
outFile.close()


↙↙↙阅读原文可查看相关链接,并与作者交流