76 lines
2.7 KiB
Python
76 lines
2.7 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""
|
|
Created on Thu Sep 26 13:44:27 2024
|
|
|
|
@author: WANGXIBAO
|
|
"""
|
|
|
|
import socket, os,datetime
|
|
from configparser import ConfigParser
|
|
|
|
def main():
|
|
udp = "udp.ini" # 配置文件默认路径
|
|
# 检测配置文件
|
|
CheckCfgIniData(udp)
|
|
|
|
# 从配置文件中读取IP和端口
|
|
config = ConfigParser()
|
|
config.read(udp, encoding='utf-8')
|
|
IP = config.get('NetConfig', 'IP')
|
|
port = config.get('NetConfig', 'port')
|
|
udp_addr = (IP, int(port))
|
|
|
|
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
print("绑定地址", udp_addr)
|
|
# 绑定端口
|
|
try:
|
|
udp_socket.bind(udp_addr)
|
|
print("开始监听。。。")
|
|
except Exception as e:
|
|
print(f"Error reading configuration: {e}")
|
|
return None
|
|
# 等待接收对方发送的数据
|
|
while True:
|
|
try:
|
|
recv_data = udp_socket.recvfrom(1024) # 1024表示本次接收的最大字节数
|
|
# 打印接收到的数据
|
|
line_utf8 = recv_data[0].decode('utf-8',errors='replace')
|
|
print("[From %s:%d]:%s" % (recv_data[1][0], recv_data[1][1], line_utf8))
|
|
|
|
|
|
line = line_utf8.split(',')
|
|
if len(line) ==2:
|
|
sav_name = line[0] +'_'+ datetime.datetime.now().strftime("%Y-%m-%d")+'.txt'
|
|
sav_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:23] +" " +line[1]
|
|
with open(sav_name, mode='a', newline='',encoding='utf-8', errors='replace') as file:
|
|
file.write(sav_str)
|
|
else:
|
|
sav_name = datetime.datetime.now().strftime("%Y-%m-%d")+'.log'
|
|
sav_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:23] +" " +line_utf8
|
|
with open(sav_name, mode='a', newline='',encoding='utf-8', errors='replace') as file:
|
|
file.write(sav_str)
|
|
|
|
except socket.error as e:
|
|
print(f"Socket error: {e}")
|
|
break # 处理错误后退出循环
|
|
|
|
def CheckCfgIniData(udp):
|
|
if not os.path.exists(udp):
|
|
config = ConfigParser()
|
|
config.add_section('NetConfig')
|
|
config.set('NetConfig', 'IP', '127.0.0.1')
|
|
config.set('NetConfig', 'port', '9000')
|
|
with open(udp, 'w', encoding='utf-8') as f:
|
|
config.write(f)
|
|
|
|
config = ConfigParser()
|
|
try:
|
|
config.read(udp, encoding='utf-8')
|
|
IP = config.get('NetConfig', 'IP')
|
|
port = config.get('NetConfig', 'port')
|
|
print(f"Configuration read successfully: {IP}, {port}")
|
|
except Exception as e:
|
|
print(f"Error reading configuration: {e}")
|
|
|
|
if __name__ == '__main__':
|
|
main() |