python 创建TCPServer 实现心跳数据发送 以及读取16进制 文件数据 逐条发送
数据格式
fbfa01014444000608021202080612
转换后格式
b’\xfb\xfa\x01\x01DC\x00\x01\x32\x34’
Creat_TcpServer_Socket 方法
def Creat_TcpServer_Socket():
host = "" # 服务器端可以写"localhost",可以为空字符串"",也为本机IP地址
port = 9999 # 设置端口
socket_fd = st.socket()
print(host)
socket_fd.bind((host, port))
socket_fd.listen(5)
while True:
global connlist
connlist,addr = socket_fd.accept() # 被动接受TCP客户端连接,(阻塞式)等待连接的到来,需要一个新的连接用来发送数据
print('连接地址:', addr)
print('clientconnlist:', connlist)
d = thread.Thread(target=read_line_txt, args=())
d.start()
d = thread.Thread(target=read_line_txt2, args=())
d.start()
break
while True:
data = connlist.recv(1024) # 接收数据
print('recive:', data) # 打印接收到的数据
#fa fb 01 01 44 43 00 01 01 fd
#FB FA 01 01 44 43 00 01 32 34
connlist.send(b'\xfb\xfa\x01\x01DC\x00\x01\x32\x34')
time.sleep(2)
read_line_txt 按行读取txt文件
'''
按行读取txt文件
'''
def read_line_txt():
var = "./warningdata.txt"
while True:
if connlist != None:
fd = open(var)
lines = fd.readlines()
for line in lines:
print("warning",line)
# print(type(line))
# senddata = str2byte(line)
# print(senddata)
line = line.strip('\n')
# print(line.encode())
# print(binascii.a2b_hex(line.encode()))
connlist.send(binascii.a2b_hex(line.encode()))
time.sleep(1)
fd.close()
time.sleep(6)
6进制转换 转换成python认识的bite格式
'''
16进制转换 转换成python认识的bite格式
'''
def str2byte(s):
base = '0123456789ABCDEF'
i = 0
s=s.upper()
s1 = ''
while i < (len(s)-1):
c1 = s[i]
c2 = s[i + 1]
i += 2
b1 = base.find(c1)
b2 = base.find(c2)
if b1 == -1 or b2 == -1:
return None
# print(((b1 << 4) + b2))
# print(hex(((b1 << 4) + b2)))
# s1 += hex(((b1 << 4) + b2))
s1 += chr(((b1 << 4) + b2))
# s1.append(hex((b1 << 4) + b2))
return s1
main 函数
if __name__ == '__main__':
# 创建两个线程
try:
t = thread.Thread(target=Creat_TcpServer_Socket, args=())
t.start()
# thread.start_new_thread(Creat_TcpServer_Socket(), ("Thread-1", 2,))
# thread.start_new_thread(read_line_txt(), ("Thread-2", 4,))
except:
print("Error: unable to start thread")