Sending files through sockets - Python

Asked

Viewed 2,840 times

0

I’m 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 Client) always lacks some bytes and some other bytes are modified, as I could see by the analysis of the sent file and the received file in a hexadecimal editor.

I based other scripts on the internet (I tested them, and they worked perfectly), but of these I took only the logic so that I could build my own. But still I could not find my mistake, which persisted. If you succeed, I ask you to indicate to me the mistake I am making. My codes are just below.

Note: The test file I am sending is exactly 6053 bytes, and I am sending it at once, but previously I was going through the file in a loop and sending the file in smaller parts. Even though it wasn’t working, I tried to make the script as simple 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!'

1 answer

1


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

fyle = open(flname,'wb')

(Also no "+" is required if you will only 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. That’s because sockets don’t have the notion of "file" or "message" by themselves - you end up having to implement another protocol - no matter how small, to be able to use sockets. For example: in this case you have encoded in the program itself the name and size of the file you will transfer. But in a system in production, that information would have to come through the network as well.

Higher-level protocols made over the socket exist - such as http, ftp, rsync, git - itself, and are available both directly in the standard Python library, and there are several helper packages to facilitate their use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.