通讯协议三、使用python简单模拟http实现过程

Posted by DDW on 06-26,2021

一、服务端

import socket
import time
import json

# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # SOCK_STREAM  TCP

# 设置IP地址和端口号
server_address = ('localhost', 8888)

# 绑定IP地址和端口号
server_socket.bind(server_address)

# 监听客户端连接数的配置
server_socket.listen(2)
print('Waiting for client connection...')
while True:
    # 等待客户端连接,获取通道和地址
    client_socket, client_address = server_socket.accept()
    print('Client connected:', client_address)

    # 接收客户端消息
    data = client_socket.recv(1024).decode("utf-8")
    print('Received message:', data)
    json_data = json.loads(data)#解包josn字符串。
    # 开始解包获取的消息,跟基本socket不同的是,这个包是json的字符串,可转变成字典结构。
    path = ["order", "login"]
    if json_data["path"] not in path:#入参验证
        message = {"code": 404, "body": {"code": -2009, "msg": "route not exits"}}
    else:
        if json_data["path"] == "order":
            # 查询数据库的订单
            sql_res = {"123": {"price": 89, "address": "guangzhou"}, "1234": {"price": 89, "address": "guangzhou"}}
            if sql_res.get(json_data["data"]["order_id"]) is None:
                message = {"code": 403, "body": {"code": -2010, "msg": "order_id error"}}
            else:
                message = {"code": 200, "body": {"code": 0, "data": sql_res[json_data["data"]["order_id"]]}}
        else:
            message = {"code": 500, "body": {"code": 0, "msg": "api error"}}

    message = json.dumps(message)
    client_socket.sendall(message.encode("utf-8"))

    # 关闭客户端连接
    client_socket.close()

二、客户端

import socket
import time
import json

# 创建socket对象
import time


def http_func(url, data):
   # 创建socket对象
   client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

   # 设置IP地址和端口号 解析端口号和IP地址
   xieyi_lst = str(url).split("://")
   xieyi = xieyi_lst[0]
   lst = xieyi_lst[1]
   path_lst = lst.split("/")
   path = path_lst[1]
   lst = path_lst[0]
   ip_port = lst.split(":")
   ip = ip_port[0]
   port = int(ip_port[1])
   server_address = (ip, port)

   # 连接到服务器
   client_socket.connect(server_address)

   # 发送消息
   re_data = {
       "data": data,
       "path": path
   }
   message = json.dumps(re_data)#一般http请求体为json字符串,把字典转变为Json字符串
   client_socket.sendall(message.encode("utf-8"))

   # 接收响应消息
   data = client_socket.recv(1024).decode("utf-8")
   data = json.loads(data)

   status_code = data["code"]
   text = data["body"]

   # 关闭连接
   client_socket.close()

   return status_code, text


if __name__ == '__main__':
   url = "http://127.0.0.1:8888/aaa"
   data = {
       "order_id": "123"
   }
   if url.startswith("http://"):
       re_func = http_func
   else:
       re_func = None
   status_code, text = re_func(url, data)
   print(status_code)
   print(text)