Python Http 多客户端和服务器(串行)

本文提供了一个使用Python实现的批量发起HTTP请求的示例代码。该代码通过遍历预设的服务器和客户端列表,从不同的客户端地址向多个服务器发送GET请求,并读取响应数据。此外,还展示了如何配置HTTP连接的调试级别、超时时间和源地址。
#!/usr/bin/env python
# coding=utf8
# si.hairui, 2016.11.24
# Http Client, Python 2.7.5

import httplib

# 服务器信息
HTTP_SERVER_LIST = [
    {'ip': "192.168.0.235", 'port': 80, 'filepath': "/web/video/smartdeer.mp4"},
    {'ip': "192.168.0.236", 'port': 80, 'filepath': "/web/video/toystory.mp4"}
]

# 客户端信息列表
HTTP_CLIENT_LIST = [
    {'ip': "192.168.0.218", 'port': 7575},
    {'ip': "192.168.0.219", 'port': 7575},
    {'ip': "192.168.0.220", 'port': 2434},
    {'ip': "192.168.0.221", 'port': 2434}
]

# 轮询服务器和客户端发起HTTP请求
for httpServer in HTTP_SERVER_LIST:
    for httpClient in HTTP_CLIENT_LIST:
        try:
            myHttpConn = httplib.HTTPConnection(httpServer['ip'], httpServer['port'],
                                                source_address=(httpClient['ip'], httpClient['port']))
            myHttpConn.debuglevel = 0  # 调试模式开关
            myHttpConn.timeout = 3  # 设置连接超时等待(单位:s
            if 0 == myHttpConn.debuglevel:
                print "---- Http Request ----"
                print httpClient['ip'] + ":", httpClient['port'], \
                    " --> " + httpServer['ip'], httpServer['port'], ": " + httpServer['filepath']

            myHttpConn.request("GET", httpServer['filepath'])  # 资源路径以“/”开始

            myHttpResp = myHttpConn.getresponse()
            if 0 == myHttpConn.debuglevel:
                print myHttpResp.status, myHttpResp.reason  # 响应码和状态信息
                # 此处必须读响应内容,如果不读取,buff将溢出!!!
                data1 = myHttpResp.read()
                pass
        except:
            print "Exception!"
        finally:
            # print data1   # 打印响应内容
            print "Http(%s:%s --> %s:%s) will be closed!" % \
                  (httpClient['ip'], str(httpClient['port']), httpServer['ip'], str(httpServer['port']))
            myHttpConn.close()  # 关闭连接


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值