Sending files via sockets - Python

0

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!'
    
asked by anonymous 12.07.2017 / 21:59

1 answer

1

You have to open the file in binary mode - especially if you are using Python 3.x - this is done by putting the letter "b" after the "w":

fyle = open(flname,'wb')

(Also you do not need the "+" if you're just going to write to the file).

It's probably the only problem you're having right now - but bear in mind that using "pure" sockets is not the most appropriate way to transfer files between different systems. This is because sockets do not have the notion of "file" or "message" by themselves - you end up having to implement another protocol - however minimal, to be able to use sockets. For example, in this case you have coded the name and size of the file to be transferred in the program itself. But on a production system, this information would have to come through the network as well.

Highest-level protocols made above the socket exist - such as http, ftp, rsync, git itself - and are available both directly in the standard Python library, as there are several auxiliary packages for ease of use. >     

13.07.2017 / 04:51