Files
Feeding_control_system/TCPServer.py

134 lines
5.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import socket
import threading
import json
import time
from datetime import datetime
class TCPServer:
def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.server_socket = None
self.client_socket = None
self.client_address = None
self.running = False
def start_server(self):
"""启动TCP服务端"""
try:
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(1)
self.running = True
print(f"TCP服务端已启动监听 {self.host}:{self.port}")
while self.running:
try:
self.client_socket, self.client_address = self.server_socket.accept()
print(f"客户端已连接: {self.client_address}")
# 启动客户端处理线程
client_thread = threading.Thread(target=self.handle_client)
client_thread.daemon = True
client_thread.start()
except Exception as e:
if self.running:
print(f"接受客户端连接时出错: {e}")
except Exception as e:
print(f"启动服务端时出错: {e}")
finally:
self.stop_server()
def handle_client(self):
"""处理客户端通信"""
try:
while self.running and self.client_socket:
try:
# 设置接收超时
self.client_socket.settimeout(1.0)
# 接收客户端数据
data = self.client_socket.recv(1024)
if not data:
break
# 解析JSON数据
message = data.decode('utf-8')
json_data = json.loads(message)
# 处理客户端返回的异常数据
self.process_client_data(json_data)
except socket.timeout:
# 超时继续循环
continue
except json.JSONDecodeError as e:
print(f"解析JSON数据时出错: {e}")
except Exception as e:
print(f"处理客户端数据时出错: {e}")
except Exception as e:
print(f"客户端处理线程出错: {e}")
finally:
self.disconnect_client()
def process_client_data(self, json_data):
"""处理客户端返回的数据"""
try:
cmd = json_data.get("cmd")
timestamp = json_data.get("timestamp")
if cmd == "production_error":
print(f"收到异常生产通知 - 时间: {timestamp}")
# 调用update_custom_table_status更新数据库状态
try:
update_custom_table_status("异常生产")
print("数据库状态已更新为: 异常生产")
except Exception as e:
print(f"更新数据库状态时出错: {e}")
elif cmd == "interrupt_error":
print(f"收到中断生产通知 - 时间: {timestamp}")
# 调用update_custom_table_status更新数据库状态
try:
update_custom_table_status("中断生产")
print("数据库状态已更新为: 中断生产")
except Exception as e:
print(f"更新数据库状态时出错: {e}")
else:
print(f"收到未知命令: {cmd}")
except Exception as e:
print(f"处理客户端数据时出错: {e}")
def send_data(self, data):
"""向客户端发送数据"""
try:
if self.client_socket and self.running:
json_data = json.dumps(data, ensure_ascii=False)
self.client_socket.send((json_data + "\n").encode('utf-8'))
print(f"已发送数据: {json_data}")
return True
except Exception as e:
print(f"发送数据时出错: {e}")
return False
def disconnect_client(self):
"""断开客户端连接"""
if self.client_socket:
self.client_socket.close()
self.client_socket = None
print("客户端已断开连接")
def stop_server(self):
"""停止服务端"""
self.running = False
if self.client_socket:
self.client_socket.close()
if self.server_socket:
self.server_socket.close()
print("TCP服务端已停止")