[Python] Python Socket 发送和接收十六进制数



需求:Python通过TCP/IP协议向socket server发送16进制命令,按10进制接收返回结果,并转成ASCII码。


Python十六进制转成十进制

例:16进制的3F转成十进制:int('3F',16)

Python十进制数转成ASCII码

例:10進制的55轉成ASCII碼:chr(55)


脚本:

import pymysql
import socket
import struct
import binascii
import time,datetime

def sql_insert(sql):
    conn = pymysql.connect(host="10.xxx.x.xx",port=3306,user="xxxx",password="xxxx",database="db_name")
    cur=conn.cursor()
    cur.execute(sql)
    conn.commit()
    conn.close()

def main():
    rectime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    try:
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.connect(('10.xxx.xxx.xxx',xxxx))
        req = struct.pack('8B', int('3F', 16), int('20', 16), int('63',16), int('31',16), int('0D',16), int('0A',16), int('0D',16), int('0A',16))
        sock.send(req)

        time.sleep(1)

        rec = sock.recv(1024)
        rec1 = struct.unpack('6B',rec)
        temp = int(chr(rec1[2]))*100 + int(chr(rec1[3]))*10 + int(chr(rec1[4]))
        sql = "insert into tb_name (temperature,rectime) values ('%s','%s')" % (temp,rectime)
        sql_insert(sql)
        sock.close()
    except Exception as e:
        print(e)

if __name__ == '__main__':
    main()

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页