I am studying sockets, using Python, and tried to make a script to send (Server) and receive (Client) files through sockets. However the script does not work as expected, the final file (received by the Client) always lacks a few bytes and some other bytes are modified, as I could see from the analysis of the sent file and the received file in a hexadecimal editor.
I took other scripts on the internet as a basis (I tested them, and they worked perfectly), but I just took the logic so I could build my own. But still I could not find my mistake, which persisted. If you can, please let me know the mistake I'm making. My codes are just below.
Note: The test file I am sending is exactly 6053 bytes, and I am sending it at one time, but I was previously browsing the file in a loop and sending the file in smaller parts. Even though it was not working, I tried to simplify the script as much as possible.
Server.py
# -*- coding: utf-8 -*-
import socket
import os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('',1112))
print 'Socket criado!'
sock.listen(5)
print 'Esperando conexão...'
conn, addr = sock.accept()
print 'Nova conexão de',addr,'!'
#Abrir arquivo
flname = 'C:\Program Files (x86)\arquivo_teste.jpg'
fyle = open(flname, 'rb')
kar = fyle.read(6053)
conn.send(kar)
print 'Arquivo enviado!'
fyle.close()
conn.close()
sock.close()
Client.py
# -*- coding: utf-8 -*-
import socket
import os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1',1112))
flname = 'C:\Program Files (x86)\recebido.jpg'
fyle = open(flname,'w+')
print 'Iniciando...'
fyle.write(sock.recv(6053))
fyle.close()
sock.close()
print 'Arquivo enviado!'