多線程socket壓力測試

江湖小火

#!/user/bin/env python
#-*- encoding:utf-8 -*-
import socket
import thread,threading

sockIndex = 1

def connToServer ():
    global sockIndex
    #創建一個socket連接到127.0.0.1:8081,併發送內容
    conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    conn.connect(("127.0.0.1", 8081))
    conn.send("hi,I'm NO."+ str(sockIndex))
    print sockIndex
    sockIndex = sockIndex + 1
    while True:
    #等待服務端返回數據,並輸出
        rev = conn.recv(1024)
        print 'get server msg:' + str(rev)
        break
threads = []
times = 20000
#併發
for i in range(0,times):
    t = threading.Thread(target=connToServer())
    threads.append(t)
for i in range(0,times):
    threads[i].start()
for i in range(0,times):
    threads[i].join()


 

蘿蔔大愛兔斯基

# Python version 3.3
__author__ = 'Toil'

import sys, getopt
import threading

def httpGet(url, file):
    import http.client
    conn = http.client.HTTPConnection(url)

    conn.request("GET", file)
    r = conn.getresponse()
    #print(r.getheaders())

    while not r.closed:
        r.read(200)

    conn.close()

def Usage():
    print('''
    Options are:
    -c concurrency  Number of multiple requests to make
    -u host         The host
    -f file         File on web

    Example: httpget.py -c 100 -u www.example.com -f /
    ''')

if __name__ == '__main__':
    opts, args = getopt.getopt(sys.argv[1:], "hc:u:f:")
    global u, c, f
    for op, value in opts:
        if op == '-c':
            c = int(value)
        elif op == '-u':
            u = value
        elif op == '-f':
            f = value
        elif op == '-h':
            Usage()
            sys.exit(0)
        else:
            sys.exit(0)

    threads = []
    times = c

    print('Test for ', u, f)
    print('waiting...')
    for i in range(0, times):
        t = threading.Thread(target=httpGet(u, f))
        threads.append(t)
    for i in range(0, times):
        threads[i].start()
    for i in range(0, times):
        threads[i].join()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章