在python中创建多线程服务器

时间:2015-12-16 17:35:34

标签: python multithreading sockets http

我是在python中实现多线程Web服务器的新手。我搜索了互联网并找到了一些资源来实现它。之后我通过这个命令在apachebench中进行了测试:

ab -n 1000 -c 5 localhost:8888 /

此命令的结果:

Concurrency Level:      5
Time taken for tests:   1.692 seconds
Complete requests:      1000
Failed requests:        0
Requests per second:    591.16 [#/sec] (mean)
Time per request:       8.458 [ms] (mean)
Time per request:       1.692 [ms] (mean, across all concurrent requests)

ab -n 1000 -c 100 localhost:8888 /

结果:

Concurrency Level:      100
Time taken for tests:   1.699 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      12078000 bytes
HTML transferred:       12000000 bytes
Requests per second:    588.50 [#/sec] (mean)
Time per request:       169.923 [ms] (mean)
Time per request:       1.699 [ms] (mean, across all concurrent requests)
Transfer rate:          6941.33 [Kbytes/sec] received

现在,我的问题是为什么这些值(测试所需的时间和每秒请求数量)不会发生变化?任何人都可以解释这个测试结果吗?

代码:

import thread
import socket
import sys

def threadFunction(client_connection,client_address):
    print 'Client thread created..'
    request = client_connection.recv(1024)
    print request
    if request=="":
    sys.exit()
    client_connection.send("HTTP/1.1 400 bad request\nContent-Type: text/html; charset=UTF-8\nContent-Lenght: "+b)
    client_connection.close()

HOST, PORT = '', 8888

listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(100)


while True:
    print 'Serving HTTP on port %s ...' % PORT
    client_connection, client_address = listen_socket.accept()
    print 'client_connection: %s , client_address : %s' % (client_connection,client_address)
    try:
                thread.start_new_thread( threadFunction, (client_connection,client_address) ) 
    except IOError:
        print "Failed in initialize thread.."
listen_socket.close() 

1 个答案:

答案 0 :(得分:1)

实际上Apache是​​一个单线程基准测试工具,测试时间是:'ab'开始测试的时间..

并发与线程

请注意,ApacheBench只使用一个操作系统线程,而不管并发级别(由-c参数指定)。在某些情况下,特别是在对高容量服务器进行基准测试时,单个ApacheBench实例本身就是一个瓶颈。在具有多个处理器核心的硬件上使用ApacheBench时,可以并行使用其他ApacheBench实例,以更充分地使目标URL饱和。