功能:客戶端可以向服務器發(fā)送get,post等請求,而服務器端可以接收這些請求,并返回給客戶端消息。
成都網(wǎng)站制作、網(wǎng)站設計、外貿(mào)網(wǎng)站建設服務團隊是一支充滿著熱情的團隊,執(zhí)著、敏銳、追求更好,是創(chuàng)新互聯(lián)的標準與要求,同時竭誠為客戶提供服務是我們的理念。創(chuàng)新互聯(lián)把每個網(wǎng)站當做一個產(chǎn)品來開發(fā),精雕細琢,追求一名工匠心中的細致,我們更用心!
客戶端:
#coding=utf-8
import http.client
from urllib import request, parse
def send_get(url,path,data):#get請求函數(shù)
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請求函數(shù)
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("----------發(fā)送get請求:-----------")
send_get(url,path="",data="None")
elif command=='post':
print("----------發(fā)送post請求-----------")
send_post(url, path="",data=datas,header=headers)
elif command =='put':
print("----------發(fā)送put請求-----------")
file = input("輸入要發(fā)送的文件名:")
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("----------發(fā)送head請求:-----------")
send_head(url, path="", data=datas, header=headers)
elif command=='option':
print("----------發(fā)送option請求:-----------")
send_option(url,path="",data=datas,header=headers)
elif command=='delete':
print("----------發(fā)送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):
# 為這個客戶端返回數(shù)據(jù)
# 1.接收瀏覽器發(fā)過來的請求,即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格式的數(shù)據(jù)給瀏覽器
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()
# 準備發(fā)給瀏覽器的數(shù)據(jù) -- header
response = "HTTP/1.1 200 OK\r\n"
response += "\r\n"
new_socket.send(response.encode("utf-8"))
new_socket.send(html_content)
# 關(guān)閉套接字
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格式的數(shù)據(jù)給瀏覽器
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格式的數(shù)據(jù)給瀏覽器
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格式的數(shù)據(jù)給瀏覽器
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"))
# 關(guān)閉套接字
new_socket.close()
def main():
# 用來完成整體的控制
# 1.創(chuàng)建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2.綁定
tcp_server_socket.bind(("0.0.0.0", 8100))
# 3.變?yōu)楸O(jiān)聽套接字
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()
# 關(guān)閉監(jiān)聽套接字
tcp_server_socket.close()
if __name__ == '__main__':
main()
分享名稱:如何用Python實現(xiàn)http客戶端和服務器
標題網(wǎng)址:http://redsoil1982.com.cn/article16/dsogcgg.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供面包屑導航、建站公司、靜態(tài)網(wǎng)站、電子商務、網(wǎng)站設計、微信公眾號
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)