69 lines
2.4 KiB
Python
69 lines
2.4 KiB
Python
#!/usr/bin/python3
|
||
# coding= utf-8
|
||
|
||
import socket
|
||
import sys
|
||
import struct
|
||
import json
|
||
|
||
# 本机信息
|
||
import time
|
||
|
||
from util.simple_sqlite3_tool import SimpleSQLite3Tool
|
||
|
||
host_ip = socket.gethostbyname(socket.gethostname())
|
||
# 组播组IP和端口
|
||
mcast_group_ip = '224.1.1.1'
|
||
mcast_group_port = 2234
|
||
|
||
|
||
def receiver():
|
||
# 建立接收 udp socket
|
||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||
# linux能绑定网卡这里绑定组播IP地址不会服错,windows没法绑定网卡只能绑定本网卡IP地址
|
||
if "linux" in sys.platform:
|
||
# 绑定到的网卡名,如果自己的不是eth0则修改
|
||
nic_name = 0
|
||
# 监听的组播地址
|
||
sock.setsockopt(socket.SOL_SOCKET, 25, nic_name)
|
||
sock.bind((mcast_group_ip, mcast_group_port))
|
||
else:
|
||
sock.bind((host_ip, mcast_group_port))
|
||
# 加入组播组
|
||
mq_request = struct.pack("=4sl", socket.inet_aton(mcast_group_ip), socket.INADDR_ANY)
|
||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mq_request)
|
||
# 设置非阻塞
|
||
sock.setblocking(True)
|
||
while True:
|
||
try:
|
||
data, address = sock.recvfrom(4096)
|
||
sql_tool = SimpleSQLite3Tool("../dms_client.db")
|
||
data2 = json.loads(data)
|
||
# 若组播数据不正确
|
||
if len(data2) < 3:
|
||
return
|
||
# 若数据已存在
|
||
res1 = sql_tool.query("select * from data_list where collection_code=? and file_name=?;", (data2.collectionCode,data2.filename))
|
||
if len(res1) != 0:
|
||
return
|
||
print(res1)
|
||
# 存入归档数据
|
||
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
||
res2 = sql_tool.execute("insert into data_list "
|
||
"(file_path,file_name,collection_code,archive_status,created_time) values (?,?,?,?,?);",
|
||
(data2.file_path, data2.file_name, data2.collection_code, 0, current_time))
|
||
print(res2)
|
||
sql_tool.close()
|
||
except socket.error as e:
|
||
print(f"while receive message error occur:{e}")
|
||
else:
|
||
print("Receive Data!")
|
||
print("FROM: ", address)
|
||
print("DATA: ", data.decode('utf-8'))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
receiver()
|