服务端脚本
#encoding:utf-8
import socket
#创建一个套接字,走默认参数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))
#设置客户端监听
tcp.listen(1)
#设置接收buff和发送buff
recv_buff=tcp.getsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF)
send_buff=tcp.getsockopt(socket.SOL_SOCKET,socket.SO_SNDBUF)
#循环接收客户端数据并发送
while True:
print("waiting....")
client,c_draa=tcp.accept()
print("客户端地址:",c_draa)
#接收客户端数据
c_data=client.recv(4096)
c_data=str(c_data,'utf-8')
print("打印客户端接收数据",c_data)
#提取请求头的请求方法
header=c_data.split('\r\n')
print("请求头按回车和换行进行分组",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"}'
# 给客户端返回响应数据
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"}'
# 给客户端返回响应数据
client.sendall(res.encode())
else:
print("请求异常响应报文")
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"}'
# 给客户端返回响应数据
client.sendall(res.encode())
#关闭客户端连接
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("打印响应:", 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)