python使用tcp传输图片数据

【python使用tcp传输图片数据】本文实例为大家分享了python使用tcp传输图片数据的具体代码,供大家参考,具体内容如下
数据包格式如下
python使用tcp传输图片数据
文章图片

客户端:

import socketimport 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'\xff\xaa\xff\xaa')#以二进制方式读取图片picData = https://www.it610.com/article/open('1.jpg', 'rb')picBytes = picData.read()#图片大小picSize = len(picBytes)#数据体长度 = guid大小(固定) + 图片大小datalen = 64 + picSize#组合数据包arrBuf += bytearray(datalen.to_bytes(4, byteorder='little'))guid = 23458283482894382928948arrBuf += bytearray(guid.to_bytes(64, byteorder='little'))arrBuf += picBytessock.sendall(arrBuf)sock.close() if __name__ == '__main__':main()

服务端:
import socketserverimport osimport sysimport timeimport threading ip_port=("172.18.0.3",19984) class MyServer(socketserver.BaseRequestHandler):def handle(self):print("conn is :",self.request) # connprint("addr is :",self.client_address) # addrwhile True:try:self.str = self.request.recv(8)data = https://www.it610.com/article/bytearray(self.str)headIndex = data.find(b'\xff\xaa\xff\xaa')print(headIndex)if headIndex == 0:allLen = int.from_bytes(data[headIndex+4:headIndex+8], byteorder='little')print("len is ", allLen) curSize = 0allData = https://www.it610.com/article/b''while curSize < allLen:data = https://www.it610.com/article/self.request.recv(1024)allData += datacurSize += len(data) print("recv data len is ", len(allData))#接收到的数据,前64字节是guid,后面的是图片数据arrGuid = allData[0:64]#去除guid末尾的0tail = arrGuid.find(b'\x00')arrGuid = arrGuid[0:tail]strGuid = str(int.from_bytes(arrGuid, byteorder = 'little')) #for testprint("-------------request guid is ", strGuid)imgData = https://www.it610.com/article/allData[64:]strImgFile ="2.jpg"print("img file name is ", strImgFile) #将图片数据保存到本地文件with open(strImgFile, 'wb') as f:f.write(imgData)f.close()breakexcept Exception as e:print(e)break if __name__ == "__main__":s = socketserver.ThreadingTCPServer(ip_port, MyServer)print("start listen")s.serve_forever()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读