首页 > 编程语言 >如何用Python实现http客户端和服务器

如何用Python实现http客户端和服务器

时间:2022-10-09 22:24:13浏览次数:72  
标签:r1 http name Python header socket print path 客户端

功能:客户端可以向服务器发送get,post等请求,而服务器端可以接收这些请求,并返回给客户端消息。

 

客户端:

#coding=utf-8
import http.client
from urllib import request, parse


def send_get(url,path,data):#get请求函数
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):#post请求函数
conn = http.client.HTTPConnection(url)#建立连接
conn.request("POST", path,data,header)#用request请求,将信息封装成帧
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()
def send_option(url,path,data,header):
conn = http.client.HTTPConnection(url)
conn.request("OPTION", path,data,header)
r1 = conn.getresponse()
print(r1.status, r1.reason)
data1 = r1.headers #
print(data1) #
conn.close()
def delete_option(url,path,filename,header):
conn = http.client.HTTPConnection(url)
conn.request("DELETE", path, filename, header)
r1 = conn.getresponse()
print(r1.status, r1.reason)

data1 = r1.read() #
print(data1)
conn.close()
if __name__ == '__main__':

url="localhost:8100"
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"}
while True:
command = input("输入请求的命令:")
if command =='get':
print("----------发送get请求:-----------")
send_get(url,path="",data="None")
elif command=='post':
print("----------发送post请求-----------")
send_post(url, path="",data=datas,header=headers)

elif command =='put':
print("----------发送put请求-----------")
file = input("输入要发送的文件名:")
tfile=open(file,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="E:/pythonProject2/httpweb/", filedata=filedatas, header=fileheaders)
elif command=='head':
print("----------发送head请求:-----------")
send_head(url, path="", data=datas, header=headers)
elif command=='option':
print("----------发送option请求:-----------")
send_option(url,path="",data=datas,header=headers)
elif command=='delete':
print("----------发送delete请求-----------")
file = input("输入要删除的文件名:")
fileheaders = {"Content-type": "text/plain", "Accept": "text/plain"}
delete_option(url, path="E:/pythonProject2/httpweb/", filename = file, header=fileheaders)
elif command == 'exit':
break
服务器:
# -*- coding: utf-8 -*-

import socket
import re
import os
import threading
import urllib.parse


def service_client(new_socket):
# 为这个客户端返回数据
# 1.接收浏览器发过来的请求,即http请求
# GET / HTTP/1.1
request = new_socket.recv(1024).decode('utf-8')
request_header_lines = request.splitlines()
print(request_header_lines)
data = request_header_lines[-1]
# ret = re.match(r'[^/]+(/[^ ]*)', request_header_lines[0])
ret = list(request_header_lines[0].split(' '))[1]
method = list(request_header_lines[0].split(' '))[0]
path_name = "/"

if method == 'GET':
if ret:
path = ret
path_name = urllib.parse.unquote(path) # 浏览器请求的路径中带有中文,会被自动编码,需要先解码成中文,才能找到后台中对应的html文件
print("请求路径:{}".format(path_name))

if path_name == "/": # 用户请求/时,返回咖啡.html页面
path_name = "/咖啡.html"

# 2.返回http格式的数据给浏览器
file_name = 'E:/pythonProject2/httpweb/HTML/' + path_name
try:
f = open(file_name, 'rb')
except:
response = "HTTP/1.1 404 NOT FOUND\r\n"
response += "\r\n"
response += "------file not found------"
new_socket.send(response.encode("utf-8"))
else:
html_content = f.read()
f.close()
# 准备发给浏览器的数据 -- header
response = "HTTP/1.1 200 OK\r\n"
response += "\r\n"
new_socket.send(response.encode("utf-8"))
new_socket.send(html_content)
# 关闭套接字
if method == 'POST':
if ret:
path = ret
path_name = urllib.parse.unquote(path) # 浏览器请求的路径中带有中文,会被自动编码,需要先解码成中文,才能找到后台中对应的html文件
print("请求路径:{}".format(path_name))
if path_name == "/": # 用户请求/时,返回咖啡.html页面
path_name = "/咖啡.html"

# 2.返回http格式的数据给浏览器
file_name = 'E:/pythonProject2/httpweb/HTML/' + path_name
response = "HTTP/1.1 200 OK\r\n"
response += "\r\n"
new_socket.send(response.encode("utf-8"))
new_socket.send(file_name.encode("utf-8")+' data:'.encode("utf-8")+data.encode("utf-8"))
if method == 'PUT':
if ret:
path = ret
path_name = urllib.parse.unquote(path) # 浏览器请求的路径中带有中文,会被自动编码,需要先解码成中文,才能找到后台中对应的html文件
print("请求路径:{}".format(path_name))
if path_name == "/": # 用户请求/时,返回咖啡.html页面
path_name = "/咖啡.html"

# 2.返回http格式的数据给浏览器
file_name = list(request_header_lines[0].split(' '))[1] +'test.txt'
content = data.encode('utf-8')
response = "HTTP/1.1 200 OK\r\n"
response += "\r\n"
with open(file_name, 'ab') as f:
f.write(content)
new_socket.send(response.encode("utf-8"))
new_socket.send("finish".encode("utf-8"))
if method=='HEAD':
if ret:
path =ret
path_name = urllib.parse.unquote(path)
print("请求路径:{}".format(path_name))
if path_name =="/":
path_name = "/咖啡.html"
response = "HTTP/1.1 200 ok\r\n"
new_socket.send(response.encode("utf-8"))
new_socket.send(str(request_header_lines[1:]).encode("utf-8"))
if method=='OPTION':
if ret:
path = ret
path_name = urllib.parse.unquote(path)
print("请求路径:{}".format(path_name))
if path_name == "/":
path_name = "/咖啡.html"
response = "HTTP/1.1 200 ok\r\n"
new_socket.send(response.encode("utf-8"))
new_socket.send("OPTIONS GET,HEAD,POST,PUT,DELETE".encode("utf-8"))
if method =='DELETE':
if ret:
path = ret
path_name = urllib.parse.unquote(path) # 浏览器请求的路径中带有中文,会被自动编码,需要先解码成中文,才能找到后台中对应的html文件
print("请求路径:{}".format(path_name))
if path_name == "/": # 用户请求/时,返回咖啡.html页面
path_name = "/咖啡.html"

deletename = request_header_lines[-1]
# print(path_name+deletename)
os.remove(path_name+deletename)
# 2.返回http格式的数据给浏览器
content = data.encode('utf-8')
response = "HTTP/1.1 200 OK\r\n"
response += "\r\n"
# with open(file_name, 'ab') as f:
# f.write(content)
new_socket.send(response.encode("utf-8"))
new_socket.send("finish".encode("utf-8"))
# 关闭套接字
new_socket.close()


def main():
# 用来完成整体的控制
# 1.创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 2.绑定
tcp_server_socket.bind(("0.0.0.0", 8100))
# 3.变为监听套接字
tcp_server_socket.listen(128)
while True:
# 4.等待新客户端的链接
new_socket, client_addr = tcp_server_socket.accept()
# 5.为这个客户端服务
print("为",client_addr,"服务")
t = threading.Thread(target=service_client, args=(new_socket,))
t.start()

# 关闭监听套接字
tcp_server_socket.close()


if __name__ == '__main__':
main()

标签:r1,http,name,Python,header,socket,print,path,客户端
From: https://www.cnblogs.com/subodong/p/16773902.html

相关文章

  • Python学习路程——Day10
    Python学习路程——Day10定义函数''' 函数的使用必须遵循’先定义,后调用’的原则。函数的定义就相当于事先将函数体代码保存起来,然后将内存地址赋值给函数名,函数名就是......
  • HttpClient详细梳理
    HttpClient详细梳理1、httpClientHttpClient是Apache中的一个开源的项目。它实现了HTTP标准中Client端的所有功能,使用它能够很容易地进行HTTP信息的传输。它的各个版本......
  • 【Web开发】Python实现Web服务器(Sanic)
    文章目录​​1、简介​​​​2、安装​​​​2.1安装sanic​​​​2.2安装sanic拓展​​​​2.3安装ubuntu​​​​3、示例测试​​​​3.1Hello,world​​​​3.2配......
  • 基于python的汽车销售网站设计与实现-计算机毕业设计源码+LW文档
    本科生毕业论文(设计)开题报告题目基于Python的汽车销售平台设计与实现学生姓名学  号指导教师学   院计算机科学与技术专  业计算机科学与技术职称助教选......
  • 基于python企业对账分析系统设计与实现-计算机毕业设计源码+LW文档
    就是收入支出申报 管理员审批 然后可以通过日期查到集体的交易往来。最少要有收入支出申报和审批两种账号 和日期查询记录这样开发语言:Python框架:djangoPython......
  • 学习python-Day69
    今日学习内容一、权限类的使用使用步骤:写一个类,继承BasePermission重写has_permission方法在方法中校验用户是否有权限(request.user)就是当前登录用户有权......
  • python 字典
    字典key:Value通过key(关键字)查到Value(信息值)。#1.字典的定义字典同样使用{},不过存储的是一个一个的键值对,如下列语法:#定义字典的字面量{key:Value,key:Value,...,key......
  • 案例分享-https证书链不完整导致请求失败
    背景话不多说,直接上堆栈javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIXpathbuildingfailed:sun.security.provider.certp......
  • python函数
    python函数函数引入当我们正常情况下需要统计列表中的数据之个数name_list=['jason','kevin','oscar','jerry']print(len(name_list))当len方法不可以使用后co......
  • 函数概念及python函数语法
    函数函数的应用场景函数是广泛应用于编程语言的一个方法,能够用于解决代码冗余的问题。我们来看这么一个场景:#校验程序userinfo={#用字典存储用户的状态'na......