python 服务器和客户端 学习http请求和响应报文头

来源:互联网 发布:淘宝马学武白玉城真假 编辑:程序博客网 时间:2024/05/17 01:44

学习《计算机网络自顶向下方法》时的一个课后小作业,一个简单的python 服务器和客户端,主要是为了学习和体验http请求和响应的首部。socket()的SOCK_STREAM参数表示使用TCP协议;
#coding=utf-8防止中文乱码,设置端口号:12000。
服务器代码:

#coding=utf-8from socket import *import codecsimport datetime#解析请求报文的请求形象路径def findPath(str):    try:        pathTemp=str.split(' ')[1]        pathTemp=pathTemp[1:]        path=pathTemp.replace('/','//')        return path[0]+':'+path[1:]    except:        return 1   #判断文件是否存在def findFile(path):    try:        file=open(path)        file.close()                return True    except:         return False#读文件def readFile(path):    try:        file=codecs.open(path,'r','utf-8')        str=file.read()        file.close()    except:        str= False     finally:        return str #计算时间def timeFormed(form):    now = datetime.datetime.now()    return now.strftime(form)def time():    week_day = {    0 : 'Mon',    1 : 'Tues',    2 : 'Web',    3 : 'Thur',    4 : 'Fri',    5 : 'San',    6 : 'Sun'    }    day = datetime.datetime.now().weekday()    week=week_day[day]#星期    month_dict={    0:'Jan',    1:'Feb',    2:'Mar',    3:'Apr',    4:'May',    5:'Jun',    6:'Jul',    7:'Aug',    8:'Sep',    9:'Oct',    10:'Nov',    11:'Dec'           }    now = datetime.datetime.now()    month=month_dict[int(now.strftime('%m'))]#月份    time=week+', '+timeFormed('%d')+' '+month+' '+timeFormed('%Y %H:%M:%S')    return time# print now#请求成功后的响应报文头部    def responseMessageHead(text):    responseMessage='''HTTP/1.1 200 OKConnection: keep-aliveData: Thur, 22 Mar '''+time()+''' GMTServer:PythonWebServer 1.0Last-Modified: Thur, 22 Mar 2017 19:26:03 GMTContent-Lenth: '''+ str(len(text.encode('utf-8'))) +'\nContent-Type:text/html\n\n'    return responseMessage   serverPort=12000serverSocket=socket(AF_INET,SOCK_STREAM)serverSocket.bind(('',serverPort))serverSocket.listen(6)print 'The server is ready to receive.'while 1:    connectionSocket,addr=serverSocket.accept()    sentence=connectionSocket.recv(1024)#sentence是从客户端发送的请求报文    path=findPath(sentence)    if path==1:        connectionSocket.send('404 Not Found')#被请求文档不在服务器上        #connectionSocket.send('400 Bad Request')#该请求不能被服务器理解        print 'This quest the server can\'t understand'    elif not findFile(path):        connectionSocket.send('404 Not Found')#被请求文档不在服务器上        print 'Not found the file which the client want'    else:        text=readFile(path)        reuestMessage=responseMessageHead(text)+text        reuestMessage=reuestMessage.encode('utf-8')        connectionSocket.send(reuestMessage)    connectionSocket.close()    print 'The online client is as follows:'    print 'Client\'s IP is:',addr[0],',','client\'s port is',addr[1],'\n'    print 'The client\'s request message is as follows:'    print sentence

客户端代码,这里是访问之前建立的一个E盘下文件:test.html。访问端口号12000,主机ip地址:127.0.0.1(就是本机)

#coding=utf-8from socket import *serverName='127.0.0.1'serverPort=12000clientSocket=socket(AF_INET,SOCK_STREAM)clientSocket.connect((serverName,serverPort))requestMessage='''GET /E/test.html HTTP/1.1Host: 127.0.0.1Connection: keep-aliveAccept: text/htmlUser-Agent: Mozilla/5.0Accept-Encoding: gzip, deflateAccept-Language: zh-cn,en-us'''clientSocket.send(requestMessage)modifiedSentence=clientSocket.recv(1024)print 'From Server:'print modifiedSentenceclientSocket.close()

在E盘下新建的test.html代码,这里写了一个简单的网页,utf-8防止部分情况下中文乱码:

<html>  <head>    <meta charset="utf-8" />    <title>测试python服务器</title>  </head>  <body>你好python</body></html>

eclipse上运行的效果:
服务器打印信息:
这里写图片描述

客户端打印信息:

这里写图片描述

浏览器的运行效果:
之后将他们全部关闭后重新运行服务器端,在浏览器输入网址:http://localhost:12000/E/test.html,回车,网页显示正常:
这里写图片描述

原创粉丝点击