Python Http 多客户端和服务器(串行)-- 从获取本地IP地址开始

#!/usr/bin/env python
# coding=utf8
# si.hairui, 2016.11.24
# Http Client, Python 2.7.5


#---------------------------------------------
#    模块导入
#---------------------------------------------
import socket
import httplib
import random

#---------------------------------------------
#    全局变量
#---------------------------------------------
# 打印开关
PRINT_SW = 0  #0-关,1-开
# 本地业务地址列表
CLIENT_IPS = []
# 客户端信息列表
HTTP_CLIENT_LIST = []
'''
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_SERVER_LIST = []
'''
HTTP_SERVER_LIST = [
    {"ip": "192.168.1.102", "port": 8988, 'filepath': "/image.jpeg"},
    {"ip": "192.168.1.102", "port": 8988, 'filepath': "/......"}
]
'''

#---------------------------------------------
#    函数实现
#---------------------------------------------
# 获得一个随机数,属于[a, b]
def getRandom(a, b):
    myDigit = random.randint(a, b)
    return myDigit
    
# 获取本地业务地址,放入序列svrIps, eg:getServiceIp(CLIENT_IPS)
def getServiceIp(svrIps):
    hostname = socket.gethostname()
    localIP = socket.gethostbyname(socket.gethostname())
    if PRINT_SW:
        print "Hostname:"
        print "    %s" % hostname
        print "Local IP:"
        print "    %s" % localIP
    
    ipList = socket.gethostbyname_ex(socket.gethostname())
    if PRINT_SW:
        print ipList
    for ips in ipList:
        # 过滤空序列、主机名
        if ips and (not isinstance(ips, str)): # ips是一个序列,其中每个元素是IP地址字符串
            if PRINT_SW:
                print "External IP:"
            for ip in ips:
                if ip != localIP:  # 过滤localIP(localIP不是业务地址发情况)
                    if PRINT_SW:
                        print "    %s" % ip
                    svrIps.append(ip)
                    
# 获取客户端列表,根据客户端地址构造,放入clientlist,eg: getClientInfo(HTTP_SERVER_LIST, CLIENT_IPS)
def getClientInfo(clientlist = [], clientips = []):
    if None == clientlist or None == clientips:  # 保护一下
        if PRINT_SW:
            print "Error: clientlist or clientips is None!!!"
        return
    for ips in clientips:
        dic = {}.fromkeys(["ip", "port"])
        dic["ip"] = ips
        dic["port"] = getRandom(1, 65535)
        clientlist.append(dic)
    if PRINT_SW:
        print clientlist

# 获取服务端列表,放入clientlist,eg: getServerInfo(HTTP_SERVER_LIST)
def getServerInfo(clientlist):
    # 暂时写个简单的
    clientlist.append({"ip": "192.168.1.1", "port": 80, 'filepath': "/"})
    
    
# 轮询服务器和客户端发起HTTP请求,eg: runHttpCliet(HTTP_CLIENT_LIST, HTTP_SERVER_LIST)
def runHttpCliet(clients = [], servers = []):
    if (None == clients) or (None == servers):  # 保护一下
        print "Error: clients or servers is None!!!"
        return
    for httpClient in clients:
        for httpServer in servers:
            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!"
                return
            finally:
                # print data1   # 打印响应内容
                print "    Http(%s:%s --> %s:%s) will be closed!" % \
                      (httpClient["ip"], str(httpClient["port"]), httpServer["ip"], str(httpServer["port"]))
                myHttpConn.close()  # 关闭连接
#---------------------------------------------
#    main模块
#---------------------------------------------
if __name__ == "__main__" :
    getServiceIp(CLIENT_IPS)  # 首先获取本机客户端IP
    getClientInfo(HTTP_CLIENT_LIST, CLIENT_IPS) # 构造客户端
    getServerInfo(HTTP_SERVER_LIST)  # 构造服务端
    runHttpCliet(HTTP_CLIENT_LIST, HTTP_SERVER_LIST)
    
    
    









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值