|
|
# encoding: utf-8
|
|
|
# @author: 原凯峰
|
|
|
# @contact: 2894340009@qq.com
|
|
|
# @software: pycharm
|
|
|
# @file: Connector.py
|
|
|
# @time: 2024/6/19 9:20
|
|
|
# @desc:
|
|
|
|
|
|
import socket
|
|
|
import threading
|
|
|
import sys
|
|
|
from http.server import HTTPServer, BaseHTTPRequestHandler
|
|
|
|
|
|
from Server import *
|
|
|
|
|
|
# 全局变量
|
|
|
sockets = {}
|
|
|
socket_lock = threading.Lock()
|
|
|
exit_flag = False
|
|
|
|
|
|
# 维护连接的函数
|
|
|
def KeepConnection(sock, ip, port):
|
|
|
"""
|
|
|
@author: 原凯峰
|
|
|
@param sock:
|
|
|
@param ip:
|
|
|
@param port:
|
|
|
@return:
|
|
|
"""
|
|
|
while not exit_flag:
|
|
|
data = sock.recv(1024)
|
|
|
if not data:
|
|
|
print(f"Gateway disconnected from {ip}:{port}")
|
|
|
break
|
|
|
print(f"Received from gateway ({ip}:{port}): {data.decode()}")
|
|
|
|
|
|
with socket_lock:
|
|
|
del sockets[sock]
|
|
|
|
|
|
# 连接到网关的函数
|
|
|
def ConnectToGateway(ip, port):
|
|
|
"""
|
|
|
@author: 原凯峰
|
|
|
@param ip:
|
|
|
@param port:
|
|
|
@return:
|
|
|
"""
|
|
|
global exit_flag
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
sock.connect((ip, port))
|
|
|
|
|
|
with socket_lock:
|
|
|
sockets[sock] = (ip, port)
|
|
|
|
|
|
print(f"Connected to gateway at {ip}:{port}")
|
|
|
|
|
|
threading.Thread(target=KeepConnection, args=(sock, ip, port)).start()
|
|
|
|
|
|
|
|
|
def StartHttpServer():
|
|
|
"""
|
|
|
@author: 原凯峰
|
|
|
@return:
|
|
|
"""
|
|
|
global exit_flag
|
|
|
server_address = ('', 8080)
|
|
|
httpd = HTTPServer(server_address, CORSHTTPRequestHandler)
|
|
|
print(f'Starting httpd server on port 8080...')
|
|
|
try:
|
|
|
while not exit_flag:
|
|
|
httpd.handle_request() # 使用 handle_request 替代 serve_forever 以便可以检查 exit_flag
|
|
|
except KeyboardInterrupt:
|
|
|
pass
|
|
|
finally:
|
|
|
httpd.server_close()
|
|
|
print("HTTP server stopped")
|
|
|
|
|
|
|
|
|
# 发送消息到特定网关的函数
|
|
|
def SendMessageToGateway(ip, port, message):
|
|
|
"""
|
|
|
@author: 原凯峰
|
|
|
@param ip:
|
|
|
@param port:
|
|
|
@param message:
|
|
|
@return:
|
|
|
"""
|
|
|
with socket_lock:
|
|
|
# 查找特定的网关连接
|
|
|
for sock, (stored_ip, stored_port) in sockets.items():
|
|
|
if stored_ip == ip and stored_port == port:
|
|
|
try:
|
|
|
# 发送消息,这里假设消息是字符串格式
|
|
|
sock.sendall(message.encode('utf-8'))
|
|
|
print(f"Message sent to {ip}:{port}: {message}")
|
|
|
except socket.error as e:
|
|
|
print(f"Error sending message to {ip}:{port}: {e}")
|
|
|
return # 找到并发送消息后退出函数
|
|
|
|
|
|
# 如果没有找到连接
|
|
|
print(f"No connection found for {ip}:{port}")
|
|
|
|
|
|
# 示例:发送消息到IP地址和端口
|
|
|
# 假设我们已经连接到了这个网关
|
|
|
|
|
|
|
|
|
def main():
|
|
|
global exit_flag
|
|
|
exit_flag = False # 初始化exit_flag
|
|
|
t = threading.Thread(target=StartHttpServer)
|
|
|
t.start()
|
|
|
while not exit_flag:
|
|
|
command = input("Enter command (/connect_gateway/exit): ")
|
|
|
# if command == "start_http_server":
|
|
|
# t = threading.Thread(target=StartHttpServer)
|
|
|
# t.start()
|
|
|
if command == "connect_gateway":
|
|
|
ip = input("Enter the gateway IP address: ")
|
|
|
port = int(input("Enter the gateway port: "))
|
|
|
ConnectToGateway(ip, port)
|
|
|
elif command == "exit":
|
|
|
exit_flag = True
|
|
|
print("Exiting program...")
|
|
|
break
|
|
|
else:
|
|
|
print("Unknown command")
|
|
|
|
|
|
# StartHttpServer函数修改
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
main() |