服務(wù)端腳本
#encoding:utf-8
import socket
#創(chuàng)建一個套接字拄养,走默認(rèn)參數(shù)IPV4
tcp=socket.socket()
#避免端口沖突
tcp.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
host='127.0.0.1'
port=6699
#綁定IP和端口
tcp.bind((host,port))
#設(shè)置客戶端監(jiān)聽
tcp.listen(1)
#設(shè)置接收buff和發(fā)送buff
recv_buff=tcp.getsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF)
send_buff=tcp.getsockopt(socket.SOL_SOCKET,socket.SO_SNDBUF)
#循環(huán)接收客戶端數(shù)據(jù)并發(fā)送
while True:
print("waiting....")
client,c_draa=tcp.accept()
print("客戶端地址:",c_draa)
#接收客戶端數(shù)據(jù)
c_data=client.recv(4096)
c_data=str(c_data,'utf-8')
print("打印客戶端接收數(shù)據(jù)",c_data)
#提取請求頭的請求方法
header=c_data.split('\r\n')
print("請求頭按回車和換行進(jìn)行分組",header)
#提取請求方法分組
head_methd=header[0]
#將提取的字符串用空格分組豁辉,最終提取到請求方法
head_methd=head_methd.split(' ')[0]
print("提取最終請求方法:",head_methd)
if head_methd=='GET':
print("GET請求")
content="HTTP/1.1 200 ok\r\nContent-Type: application/json;charset=utf8\r\nTIP:XcxQuery\r\n\r\n"
res= content + '{"code":"success","msg":"get respones"}'
# 給客戶端返回響應(yīng)數(shù)據(jù)
client.sendall(res.encode())
elif head_methd=='POST':
print("POST請求")
#獲取請求頭中的Content-Length長度
content_length=0
for line in header:
if line.startswith("Content-Length"):
content_length=int(line.split(":")[1])
break
#接收請求體
req_body=client.recv(content_length).decode()
print("請求體:",req_body)
content = "HTTP/1.1 200 ok\r\nContent-Type: application/json;charset=utf8\r\nTIP:XcxQuery\r\n\r\n"
res = content + '{"code":"success","msg":"post respones"}'
# 給客戶端返回響應(yīng)數(shù)據(jù)
client.sendall(res.encode())
else:
print("請求異常響應(yīng)報文")
content="HTTP/1.1 400 Bad Request\r\nContent-Type: application/json;charset=utf8\r\nTIP:null\r\n\r\n"
res=content + '{"code":"FAIL","message":"Invalid Request"}'
# 給客戶端返回響應(yīng)數(shù)據(jù)
client.sendall(res.encode())
#關(guān)閉客戶端連接
client.close()
客戶端腳本
#encoding:utf-8
import requests
import json
def http_client(url,method,data=None):
if method=="post":
headers={"Content-Type": "application/json;charset=utf8"}
res=requests.post(url,data=data,headers=headers,timeout=30)
else:
res=requests.get(url)
print("打印響應(yīng):", res.text)
print("打印header:",res.headers)
if __name__=="__main__":
#url="http://127.0.0.1:6699/login?name=lili"
url="http://127.0.0.1:6699/login"
data="{'name':'lili'}"
http_client(url,'get')
http_client(url,"post",data)