1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 【Python 基础】网络编程 - Python写一个简单的HTTP服务端和客户端 实现Client/Server交互

【Python 基础】网络编程 - Python写一个简单的HTTP服务端和客户端 实现Client/Server交互

时间:2020-02-26 07:15:02

相关推荐

【Python 基础】网络编程 - Python写一个简单的HTTP服务端和客户端 实现Client/Server交互

1.HTTP

首先讲一下http和https,详细可以去看runoob http-vs-https

基本概念

HTTP(HyperText Transfer Protocol:超文本传输协议)是一种用于分布式、协作式和超媒体信息系统的应用层协议。 简单来说就是一种发布和接收 HTML 页面的方法,被用于在 Web 浏览器和网站服务器之间传递信息。

HTTP默认工作在 TCP 协议 80 端口,用户访问网站 http:// 打头的都是标准 HTTP 服务。

HTTP

协议以明文方式发送内容,不提供任何方式的数据加密,如果攻击者截取了Web浏览器和网站服务器之间的传输报文,就可以直接读懂其中的信息,因此,HTTP协议不适合传输一些敏感信息,比如:信用卡号、密码等支付信息。

HTTPS(Hypertext Transfer Protocol Secure:超文本传输安全协议)是一种透过计算机网络进行安全通信的传输协议。HTTPS 经由 HTTP 进行通信,但利用 SSL/TLS 来加密数据包。HTTPS 开发的主要目的,是提供对网站服务器的身份认证,保护交换数据的隐私与完整性。

HTTPS 默认工作在 TCP 协议443端口,它的工作流程一般如以下方式:

1、TCP 三次同步握手 2、客户端验证服务器数字证书 3、DH 算法协商对称加密算法的密钥、hash 算法的密钥 4、SSL

安全加密隧道协商完成

5、网页以加密的方式传输,用协商的对称加密算法和密钥加密,保证数据机密性;用协商的hash算法进行数据完整性保护,保证数据不被篡改。

截至 年 6 月,Alexa 排名前 100 万的网站中有 34.6% 使用 HTTPS 作为默认值,互联网 141387

个最受欢迎网站的 43.1% 具有安全实施的 HTTPS,以及 45% 的页面加载(透过Firefox纪录)使用HTTPS。 年3

月,中国注册域名总数的 0.11%使用 HTTPS。

根据 Mozilla 统计,自 年 1 月以来,超过一半的网站流量被加密。

HTTP 与 HTTPS 区别

HTTP 明文传输,数据都是未加密的,安全性较差,HTTPS(SSL+HTTP) 数据传输过程是加密的,安全性较好。

使用 HTTPS 协议需要到 CA(Certificate Authority,数字证书认证机构) 申请证书,一般免费证书较少,因而需要一定费用。证书颁发机构如:Symantec、Comodo、GoDaddy 和 GlobalSign 等。

HTTP 页面响应速度比 HTTPS 快,主要是因为 HTTP 使用 TCP 三次握手建立连接,客户端和服务器需要交换 3 个包,而 HTTPS除了 TCP 的三个包,还要加上 ssl 握手需要的 9 个包,所以一共是 12 个包。

http 和 https 使用的是完全不同的连接方式,用的端口也不一样,前者是 80,后者是 443。

HTTPS 其实就是建构在 SSL/TLS 之上的 HTTP 协议,所以,要比较 HTTPS 比 HTTP 要更耗费服务器资源。

socket

2.Python http

具体可以参考:http — HTTP 模块

http 是一个包,它收集了多个用于处理超文本传输协议的模块:

http.client 是一个低层级的 HTTP 协议客户端;对于高层级的 URL 访问请使用 urllib.request

http.server 包含基于 socketserver 的基本 HTTP 服务类

http.cookies 包含一些有用来实现通过 cookies 进行状态管理的工具

http.cookiejar 提供了 cookies 的持久化

http 也是一个通过 http.HTTPStatus 枚举定义了一些 HTTP 状态码以及相关联消息的模块

class http.HTTPStatus

3.源码实例

server.py

#coding=utf-8import http.clientimport urllibfrom http.server import HTTPServer, BaseHTTPRequestHandlerimport jsondef start_server():data = {'result': 'this is a test'}host = ('localhost', 8981)class Resquest(BaseHTTPRequestHandler):def do_GET(self):data={"Method:":mand,"Path:":self.path}print(data)self.send_response(200)self.send_header('Content-type', 'application/json')self.end_headers()self.wfile.write(json.dumps(data).encode())def do_POST(self):length = int(self.headers['Content-Length'])post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))# You now have a dictionary of the post datadata = {"Method:": mand,"Path:": self.path,"Post Data":post_data}print(data)self.send_response(200)self.send_header('Content-type', 'application/json')self.end_headers()self.wfile.write(json.dumps(data).encode())def do_HEAD(self):data = {"Method:": mand,"Path:": self.path,"Header Content-type": self.headers.get('Content-type')}print(data)self.send_response(200)self.send_header("Content-type", "text/html")self.end_headers()self.wfile.write(json.dumps(data).encode())def do_PUT(self):data = {"Method:": mand,"Path:": self.path,"Header Content-type": self.headers.get('Content-type')}print(data)path = self.pathcontent_length = int(self.headers.get('content-length'))content = self.rfile.read(content_length)#safe_mkdir(os.path.dirname(path))with open("D:/code/pyhttp/put_datas.txt", 'ab') as outfile:outfile.write(content)self.send_response(200)self.end_headers()self.wfile.write(json.dumps(data).encode())server = HTTPServer(host, Resquest)print("Starting server, listen at: %s:%s" % host)server.serve_forever()if __name__ == '__main__':start_server()print("start server success...")

client.py

#coding=utf-8import http.clientfrom urllib import request, parsedef send_get(url,path,data):conn = http.client.HTTPConnection(url)conn.request("GET", path)r1 = conn.getresponse()print(r1.status, r1.reason)data1 = r1.read()print(data1) #conn.close()def send_post(url,path,data,header):conn = http.client.HTTPConnection(url)conn.request("POST", path,data,header)r1 = conn.getresponse()print(r1.status, r1.reason)data1 = r1.read()print(data1) #conn.close()def send_head(url,path,data,header):conn = http.client.HTTPConnection(url)conn.request("HEAD", path,data,header)r1 = conn.getresponse()print(r1.status, r1.reason)data1 = r1.headers #print(data1) #conn.close()def send_put(url,path,filedata,header):conn = http.client.HTTPConnection(url)conn.request("PUT", path,filedata,header)r1 = conn.getresponse()print(r1.status, r1.reason)data1 = r1.read() #print(data1)conn.close()if __name__ == '__main__':url="localhost:8981"data = {'my post data': 'I am client , hello world',}datas = parse.urlencode(data).encode('utf-8')headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}print("----------Send get test:-----------")send_get(url,path="/index",data="None")print("----------Send post test:-----------")send_post(url, path="/index",data=datas,header=headers)print("----------Send head test:-----------")send_head(url, path="/index", data=datas, header=headers)print("----------Send put test:-----------")tfile=open("test.txt",encoding="utf-8",mode='r')filedatas=tfile.read()fileheaders = {"Content-type": "text/plain", "Accept": "text/plain",\"content-length":str(len(filedatas))}send_put(url, path="/index", filedata=filedatas, header=fileheaders)

效果:

4.完整代码下载

/download/Datapad/19119843

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。