随笔 - 20, 文章 - 0, 评论 - 4, 阅读 - 23173

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

解析Http消息内容

Posted on   初之萌萌  阅读(42)  评论(0编辑  收藏  举报
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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')
 
   

 

相关博文:
阅读排行:
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
· 零经验选手,Compose 一天开发一款小游戏!
点击右上角即可分享
微信分享提示