-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtcp_server.py
67 lines (54 loc) · 1.84 KB
/
tcp_server.py
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
import json
import threading
import socketserver
import requests
from wxhandler import wxhandler1
# 将HOOK消息转到本脚本
class ReceiveMsgSocketServer(socketserver.BaseRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def handle(self):
conn = self.request
while True:
try:
ptr_data = b""
while True:
data = conn.recv(1024)
ptr_data += data
if len(data) == 0 or data[-1] == 0xA:
break
msg = json.loads(ptr_data)
ReceiveMsgSocketServer.msg_callback(msg)
except OSError:
break
except json.JSONDecodeError:
pass
conn.sendall("200 OK".encode())
conn.close()
@staticmethod
def msg_callback(msg):
# 打印出接收到的消息
formatted_message = json.dumps(msg, indent=4, ensure_ascii=False)
print(formatted_message)
def start_socket_server(port: int = 19099,
request_handler=ReceiveMsgSocketServer,
main_thread: bool = True) -> int or None:
ip_port = ("127.0.0.1", port)
try:
s = socketserver.ThreadingTCPServer(ip_port, request_handler)
if main_thread:
s.serve_forever()
else:
socket_server = threading.Thread(target=s.serve_forever)
socket_server.setDaemon(True)
socket_server.start()
return socket_server.ident
except KeyboardInterrupt:
pass
except Exception as e:
print(e)
return None
if __name__ == '__main__':
base_url = "http://127.0.0.1:19088"
wxhandler1(base_url).hookSyncMsg(False, 8000) # 启动微信消息同步
start_socket_server()