[英]Distortion in image while transferring file using sockets in python
When I transfer text files using this code, the text file received is exactly the same as the text file sent. 当我使用此代码传输文本文件时,收到的文本文件与发送的文本文件完全相同。 But when I use this code to transfer image files or video files, problems arise (distortion) and I don't understand why.
但是,当我使用此代码传输图像文件或视频文件时,会出现问题(失真),而且我不明白为什么。
Server code: 服务器代码:
import socket
import base64
filename = open("received.jpg","a")
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
data = conn.recv(16)
filesize = int(data)
iter = filesize//BUFFER_SIZE
i = 0
while (i < iter):
data = conn.recv(BUFFER_SIZE)
filename.write(data.decode('base64'))
if not data:
continue
i = i + 1
data = conn.recv((filesize - (iter*BUFFER_SIZE)))
filename.write(data.decode('base64'))
filename.close()
conn.close()
Client code: 客户代码:
import socket
import time
import base64
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
filename = open("test.jpg","rb")
MESSAGE = base64.b64encode(filename.read())
filesize = '%16s'%len(MESSAGE)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(filesize)
time.sleep(1)
s.send(MESSAGE)
s.close()
filename = open("received.jpg","a")
应该几乎肯定是
filename = open("received.jpg","ab")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.