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'\xff\xaa\xff\xaa')
#以二進制方式讀取圖片
picData = open('1.jpg', 'rb')
picBytes = picData.read()
#圖片大小
picSize = len(picBytes)
#數(shù)據(jù)體長度 = guid大小(固定) + 圖片大小
datalen = 64 + picSize
#組合數(shù)據(jù)包
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'\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 = 0
allData = b''
while curSize allLen:
data = self.request.recv(1024)
allData += data
curSize += len(data)
print("recv data len is ", len(allData))
#接收到的數(shù)據(jù),前64字節(jié)是guid,后面的是圖片數(shù)據(jù)
arrGuid = allData[0:64]
#去除guid末尾的0
tail = arrGuid.find(b'\x00')
arrGuid = arrGuid[0:tail]
strGuid = str(int.from_bytes(arrGuid, byteorder = 'little')) #for test
print("-------------request guid is ", strGuid)
imgData = allData[64:]
strImgFile = "2.jpg"
print("img file name is ", strImgFile)
#將圖片數(shù)據(jù)保存到本地文件
with open(strImgFile, 'wb') as f:
f.write(imgData)
f.close()
break
except Exception as e:
print(e)
break
if __name__ == "__main__":
s = socketserver.ThreadingTCPServer(ip_port, MyServer)
print("start listen")
s.serve_forever()