这篇文章主要为大家详细介绍了python使用tcp传输图片数据,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了python使用tcp传输图片数据的具体代码,供大家参考,具体内容如下
数据包格式如下
客户端:
import socket import sys HOST,PORT = "172.18.0.3",19984 def main(): sock = socket.socket(socket.AF_INET, socket.soCK_STREAM) sock.connect((HOST, PORT)) #包头标志 arrBuf = bytearray(b'xffxaaxffxaa') #以二进制方式读取图片 picData = open('1.jpg', 'rb') picBytes = picData.read() #图片大小 picSize = len(picBytes) #数据体长度 = guid大小(固定) + 图片大小 datalen = 64 + picSize #组合数据包 arrBuf += bytearray(datalen.to_bytes(4, byteorder='little')) guid = 23458283482894382928948 arrBuf += bytearray(guid.to_bytes(64, byteorder='little')) arrBuf += picBytes sock.sendall(arrBuf) sock.close() if __name__ == '__main__': main()
服务端:
import socketserver import os import sys import time import threading ip_port=("172.18.0.3",19984) class MyServer(socketserver.BaseRequestHandler): def handle(self): print("conn is :",self.request) # conn print("addr is :",self.client_address) # addr while True: try: self.str = self.request.recv(8) data = bytearray(self.str) headindex = data.find(b'xffxaaxffxaa') print(headindex) if headindex == 0: allLen = int.from_bytes(data[headindex+4:headindex+8], byteorder='little') print("len is ", allLen) curSize = 0 allData = b'' while curSize