# coding:utf-8
from socket import *
import binascii, linecache, time
ServerUrl = "127.0.0.1:900"
def SocketServer():
try:
Colon = ServerUrl.find(':')
IP = ServerUrl[0:Colon]
Port = int(ServerUrl[Colon + 1:])
# 建立socket对象
print("serval start: %s" % ServerUrl)
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# 绑定ip端口
sockobj.bind((IP, Port))
sockobj.listen(5)
i = 1
while i < 5770:#升级5660行
connection, address = sockobj.accept()
while 1:
# 读取某一行
def getline(the_file_path, line_number):
if line_number < 1:
return ''
for cur_line_number, line in enumerate(open(the_file_path, 'rU')):
if cur_line_number == line_number - 1:
return line.replace('
', '
')
return line
return ''
the_line = str(linecache.getline('E:\1.hex', i)).strip()#需要发送的hex文件
# the_line = str(linecache.getline('E:\1.hex', i))#需要发送的hex文件
ss = binascii.a2b_hex(the_line)
print(ss)
time.sleep(0.05)
def re(i):
if i <= 4659:#需要升级多少行
# 将前面对齐
if (len(str(i)) == 1):
s = hex(i)
sss = ''
for s1 in s:
if s1 == 'x':
s1 = '000'
sss = (sss + s1)
return (sss[1:])
elif (len(str(i)) == 2):
s = hex(i)
sss = ''
for s1 in s:
if s1 == 'x':
s1 = '00'
sss = (sss + s1)
return(sss[1:])
elif (len(str(i)) == 3):
s = hex(i)
sss = ''
for s1 in s:
if s1 == 'x':
s1 = '0'
sss = (sss + s1)
return(sss)
elif (len(str(i)) == 4):
s = hex(i)
sss = ''
for s1 in s:
if s1 == 'x':
s1 = ''
sss = (sss + s1)
return(sss)
# else:
# s = hex(i)
# sss = ''
# for s1 in s:
# if s1 == 'x':
# s1 = ''
# ss = (sss + s1)
# return(sss[1:])
sre = re(i)
if len(re(i))==3:
sre = '0'+sre
elif len(re(i))==5:
sre = sre[1:]
print('第'+i+'行')
connection.send(binascii.a2b_hex(sre)+binascii.a2b_hex('3a')+ss)
# connection.send(binascii.a2b_hex('3a'))
# # connection.send(binascii.a2b_hex('3a'))
# connection.send(ss)
i = i+1
connection.close()
except Exception as ex:
print(ex)
SocketServer()