python使用socket 先读取长度,在读取报文内容示例
本文实例讲述了python使用socket先读取长度,在读取报文内容。分享给大家供大家参考,具体如下:
tlpmts1:~/sbin#cattest9105.py
#-*-coding:utf-8-*-
importSocketServer
importsocket
importtime
importsys
reload(sys)
printtime.ctime()
sys.setdefaultencoding('utf-8')
classSMSsendx(object):
defSms(self):
#.decode('utf-8').encode('gbk')
host='10.4.160.71'
port=9105
print'host'+'->'+host
print'port'+'->'+str(port)
bufsize=10240
addr=(host,port)
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(20)
s.connect((host,port))
data=''
#data='007144 100443923 330600600 20170920 101020 A01 301020 10102020170926010000550744 10.4.129.21 17 01003000003 101020 0 0 10102020170926010000550744 9999 14 0000000000 10000000000000000000 0 33010000201000000459 0 1 14 1 0110111100 '
#length=len(data.encode('utf-8'))
#slen='%08d'%length
#data=slen+data
#data='00031421801020180528010000218475 L06 2018052810241220 ES999 APP ZXGY 999999999 218010 '
data='004355 173906133 330100921 ES999 9999 20190528 202020 M01 50010120190528010000002780 201010 20202020190528878173906123 0001 27 202020 01003000003 20202020190424878173906123 '
length=len(data.encode('utf-8'))
slen='%08d'%length
data=slen+data
printdata
recv_size=0
#msg=data.encode('gbk')
s.send(data)
data=s.recv(bufsize)
#printdata.strip()
length=data
printint(length)
resp=s.recv(int(length));
cur_time=time.strftime("%Y-%m-%d%H:%M:%S",time.localtime())
print("%sreceicefromserver:%s")%(cur_time,data+resp)
a=SMSsendx()
a.Sms()
printtime.ctime()
tlpmts1:~/sbin#pythontest9105.py
ThuJul 416:06:432019
host->10.4.160.71
port->9105
00000754004355 173906133 330100921 ES999 9999 20190528 202020 M01 50010120190528010000002780 201010 20202020190528878173906123 0001 27 202020 01003000003 20202020190424878173906123
539
2019-07-0416:06:43receicefromserver:000005390000
交易成功
20190528
173906133
01003000003
27
20202020190528878173906123
201010
202020
20202020190424878173906123
ThuJul 416:06:432019
更多关于Python相关内容可查看本站专题:《PythonSocket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。