from importlib.resources import path
import socket
import struct
import ctypes
import time,os
tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_ip = 'xxx.xxx.x.xxx'
server_port = xxxx
tcp_socket.connect((server_ip,server_port))
print(f"连接到服务器{server_ip}:{server_port}")
class _MSG_HEAD(ctypes.Structure):
_fields_ = [
("Type", ctypes.c_short),
("Len", ctypes.c_short),
]
#注册
class _MSG_CLIENT_REGISTER(ctypes.Structure):
_fields_ = [
("Head", _MSG_HEAD),
("clientid", ctypes.c_char*11)
]
msg_client_register = _MSG_CLIENT_REGISTER()
msg_client_register.Head.Type = 2048
msg_client_register.Head.Len = 11
msg_client_register.clientid = b"clinetid_1"
fmt1 = "<HH11s"
send_buf = struct.pack(fmt1,msg_client_register.Head.Type,msg_client_register.Head.Len,msg_client_register.clientid)
tcp_socket.send(send_buf)
print(r"发送注册信息:(2048,11,b'clinetid_1')")
from_server_msg = tcp_socket.recv(1024)
try:
fmt = "<HHii11s9siiiiii"
msg1 = struct.unpack(fmt, from_server_msg )
print(f"注册回信:{msg1}")
except:
msg1 = from_server_msg.decode("utf-8",'ignore')
print(f"注册回信:{msg1}")
#请求仪器数据流
class _MSG_CLIENT_CALL_DATA(ctypes.Structure):
_fields_ = [
("Head", _MSG_HEAD),
("MeterNo",ctypes.c_int),
("Sensor",ctypes.c_int),
("OnOff",ctypes.c_int),
]
msg_client_call_data = _MSG_CLIENT_CALL_DATA()
msg_client_call_data.Head.Type = 4192
msg_client_call_data.Head.Len = 12
msg_client_call_data.MeterNo = msg1[3]
msg_client_call_data.Sensor= 2
msg_client_call_data.OnOff = 1
fmt11 = "<HHiii"
send_buf11 = struct.pack(fmt11,msg_client_call_data.Head.Type,
msg_client_call_data.Head.Len,msg_client_call_data.MeterNo,
msg_client_call_data.Sensor,msg_client_call_data.OnOff)
print(r"发送请求仪器数据流:(4192,12,{},2,1)".format(msg1[3]))
tcp_socket.send(send_buf11)
from_server_msg11 = tcp_socket.recv(1024)
msg11 = from_server_msg11.decode("utf-8",'ignore')
try:
msg11 = struct.unpack('<HHiii', from_server_msg11)
print(f"请求仪器数据第一次回信:{msg11}")
except:
msg11 = from_server_msg11.decode("utf-8",'ignore')
print(f"请求仪器数据第一次回信:{msg11}")
while(True):
try:
from_server_msg0 = tcp_socket.recv(1024)
try:
print('获取数据流:')
fmt0 = "<HHiiI100h"
rest = struct.unpack(fmt0, from_server_msg0)
print(rest[5:])
uuid_str = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime())
tmp_file_name ='%s.txt' % uuid_str
path = os.path.join('data',tmp_file_name)
print(path)
with open(path,'w') as f:
print(len(rest[5:]))
f.write(str(rest[5:]))
except:
rest = from_server_msg0.decode("utf-8",'ignore')
#print(from_server_msg0)
except:
break
tcp_socket.close()
python与C语言socket通信--发送、接收(解析)结构体数据
最新推荐文章于 2024-06-30 11:15:46 发布