导航

解析Http消息内容

Posted on 2022-03-02 17:36  初之萌萌  阅读(39)  评论(0编辑  收藏  举报
import socket
import threading
import requests
from urllib.parse import unquote, quote
import time

# 此类用来解析请求的方法、路径、header,body
class Request():
    def __init__(self, r):
        self.content = r
        self.method = r.split()[0]
        self.path = r.split()[1]
        self.body = r.split('\r\n\r\n', 1)[1]

    def parse_path(self):
        index = self.path.find('?')
        if index == -1:
            return self.path, {}
        else:
            path, query_string = self.path.split('?', 1)
            return path, query_string

    def headers(self):
        header_content = self.content.split('\r\n\r\n', 1)[0].split('\r\n')[1:]
        result = {}
        for line in header_content:
            k, v = line.split(': ')
            result[quote(k)] = quote(v)
        return result


# 平台回复
def login(sock, content, client_ip):
    r = Request(content)
    path, _ = r.parse_path()
    login_response = 'HTTP/1.1 200 OK\r\n'
    login_response += 'Connection: keep-alive\r\n'
    login_response += '\r\n'
    login_response += """
    具体回复消息
    """

    if path == '具体api':
        print('收到注册消息')
        print(r.body)
        sock.send(login_response.encode())
        chunk = sock.recv(1024)
        while True:
            if chunk:
                print('接收消息:%s' % chunk)
                path = str(chunk.split()[1])
                index = path.find('?')
                if index != -1:
                    path_beat, _ = path.split('?', 1)
                else:
                    path_beat = path

                # 心跳
                if path_beat.find('HeartBeat') != -1:
                    print('收到心跳消息')
                    heartbeat_response = 'HTTP/1.1 200 OK\r\n'
                    heartbeat_response += 'Connection: keep-alive\r\n'
                    heartbeat_response += '\r\n'
                    heartbeat_response += """
                      具体内容
                        """
                    sock.send(heartbeat_response.encode())
                else:
                    pass

            chunk = sock.recv(1024)

# 处理每一个请求
def tcp_link(sock, client_ip):
        # sock.settimeout(300)
        print('\n#####Receive Message:#####')
        content = ''
        while True:
            try:
                request = sock.recv(2049).decode()
                if request:
                    # print(request)
                    login(sock, request, client_ip)
                    # break
            except:
                pass
                # sock.close()

# 开启服务器
def start_server(server_port, test_ipc_ip):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('', int(server_port)))
        s.listen(1)


        while True:
            sock, addr = s.accept()
            print(addr)
            x = str(addr).split("'")
            if str(x[1]) != str(test_ipc_ip):
                print('主动断开连接')
                sock.close()
                continue
            t = threading.Thread(target=tcp_link, args=(sock, str(x[1])))
            t.start()
    except Exception as e:
        print(e)



if __name__ == '__main__':
    # 模拟平台收到主动注册消息
    start_server(80, '192.168.0.66')