Send file with python socket

Send File via Socket

The following code establishes a client-server connection between two Python programs via the socket standard module and sends a file from the client to the server. The file transfer logic is contained in two functions: the client defines a send_file() function to send a file through a socket and inversely the server defines receive_file() to receive it. This way the functions can be easily moved from this post to other programs that already implement a client-server connection. The code is ready to send any file format and size. Python 3.8 or greater is required.

You can download both Python files and a test file to be transfered from here: send-file-via-socket.zip.

# server.py
import socket
import struct
def receive_file_size ( sck : socket . socket ):
# This funcion makes sure that the bytes which indicate
# the size of the file that will be sent are received.
# The file is packed by the client via struct.pack(),
# a function that generates a bytes sequence that
# represents the file size.
fmt = »
expected_bytes = struct . calcsize ( fmt )
received_bytes = 0
stream = bytes ()
while received_bytes < expected_bytes :
chunk = sck . recv ( expected_bytes — received_bytes )
stream += chunk
received_bytes += len ( chunk )
filesize = struct . unpack ( fmt , stream )[ 0 ]
return filesize
def receive_file ( sck : socket . socket , filename ):
# First read from the socket the amount of
# bytes that will be received from the file.
filesize = receive_file_size ( sck )
# Open a new file where to store the received data.
with open ( filename , «wb» ) as f :
received_bytes = 0
# Receive the file data in 1024-bytes chunks
# until reaching the total amount of bytes
# that was informed by the client.
while received_bytes < filesize :
chunk = sck . recv ( 1024 )
if chunk :
f . write ( chunk )
received_bytes += len ( chunk )
with socket . create_server (( «localhost» , 6190 )) as server :
print ( «Waiting for the client. » )
conn , address = server . accept ()
print ( f » < address [ 0 ] >: < address [ 1 ] >connected.» )
print ( «Receiving file. » )
receive_file ( conn , «received-image.png» )
print ( «File received.» )
print ( «Connection closed.» )
# client.py
import os
import socket
import struct
def send_file ( sck : socket . socket , filename ):
# Get the size of the outgoing file.
filesize = os . path . getsize ( filename )
# First inform the server the amount of
# bytes that will be sent.
sck . sendall ( struct . pack ( »
# Send the file in 1024-bytes chunks.
with open ( filename , «rb» ) as f :
while read_bytes := f . read ( 1024 ):
sck . sendall ( read_bytes )
with socket . create_connection (( «localhost» , 6190 )) as conn :
print ( «Connected to the server.» )
print ( «Sending file. » )
send_file ( conn , «image.png» )
print ( «Sent.» )
print ( «Connection closed.» )

To test the code, make sure to modify the send_file() and receive_file() calls with the path of the file you want to send and the path where you want to receive it. In the previous code there is a file called image.png in the same folder where both Python files are located that is received as received-image.png . Once you’ve adjusted the file names, first run the server:

Then run the client in another terminal:

The server output will look like this:

Waiting for the client. 127.0.0.1:60331 connected. Receiving file. File received. Connection closed.
Connected to the server. Sending file. Sent. Connection closed.

Источник

Передача файла через сокет в Python 3

Язык программирования Python

Следующий код устанавливает соединение клиент-сервер между двумя программами Python с помощью стандартного модуля socket и отправляет файл с клиента на сервер.

Логика передачи файлов содержится в двух функциях: клиент определяет функцию send_file() для отправки файла через сокет и, наоборот, сервер определяет функцию receive_file() для его получения.

Таким образом, вы сможете легко перенести функции из этой статьи в другие программы, которые уже реализуют соединение клиент-сервер.

Код подготовлен для отправки файлов любого формата и любого размера. Требуется Python 3.8 или выше.

Сервер:

# server.py import socket import struct def receive_file_size(sck: socket.socket): # Эта функция обеспечивает получение байтов, # указывающих на размер отправляемого файла, # который кодируется клиентом с помощью # struct.pack(), функции, которая генерирует # последовательность байтов, представляющих размер файла. fmt = " expected_bytes = struct.calcsize(fmt) received_bytes = 0 stream = bytes() while received_bytes < expected_bytes: chunk = sck.recv(expected_bytes - received_bytes) stream += chunk received_bytes += len(chunk) filesize = struct.unpack(fmt, stream)[0] return filesize def receive_file(sck: socket.socket, filename): # Сначала считываем из сокета количество # байтов, которые будут получены из файла. filesize = receive_file_size(sck) # Открываем новый файл для сохранения # полученных данных. with open(filename, "wb") as f: received_bytes = 0 # Получаем данные из файла блоками по # 1024 байта до объема # общего количество байт, сообщенных клиентом. while received_bytes < filesize: chunk = sck.recv(1024) if chunk: f.write(chunk) received_bytes += len(chunk) with socket.create_server(("localhost", 6190)) as server: print("Ожидание клиента. ") conn, address = server.accept() print(f": подключен.") print("Получаем файл. ") receive_file(conn, "image-received.png") print("Файл получен.") print("Соединение закрыто.")
Code language: PHP (php)

Клиент

# client.py import os import socket import struct def send_file(sck: socket.socket, filename): # Получение размера файла. filesize = os.path.getsize(filename) # В первую очередь сообщим серверу, # сколько байт будет отправлено. sck.sendall(struct.pack(", filesize)) # Отправка файла блоками по 1024 байта. with open(filename, "rb") as f: while read_bytes := f.read(1024): sck.sendall(read_bytes) with socket.create_connection(("localhost", 6190)) as conn: print("Подключение к серверу.") print("Передача файла. ") send_file(conn, "image.png") print("Отправлено.") print("Соединение закрыто.")
Code language: PHP (php)

Чтобы протестировать код, вы должны изменить вызовы send_file() и receive_file(), указав путь к файлу, который вы хотите отправить, и путь к файлу, в котором вы хотите его получить.

В текущем коде это файл image.png, который находится в той же папке, что и два файла Python, и принимается как image-received.png.

После этого запустите сервер:

python server.py
Code language: CSS (css)

Затем, на другом терминале, клиент:

python client.py
Code language: CSS (css)

Вывод сервера будет выглядеть следующим образом:

Ожидание клиента. 127.0.0.1:60331 подключен. Получаем файл. Файл получен. Соединение закрыто.
Code language: CSS (css)
Подключение к серверу. Передача файла. Отправлено. Соединение закрыто.

Источник

Python Socket File Transfer Send

The intention of this article is to learn how to transfer a text file over network through python program. This file transfer is based on server client model to use socket programming in python3+.

Basic Set up Diagram:

Here is the basic set up diagram to run this program.

For simplicity we will call System A as A_client and System B as B_server throughout the article.

File requirements:

We need server.py and this file should be present at server system. In our case server.py should be at B_server system.

Another two files client.py and sample.txt should be present at client system. In our case those two files should be present at A_client system.

Assumptions:

  • We should have two Linux systems with terminal access.
  • Preferable Linux flavor is Ubuntu.
  • Python3 should be installed.
  • Both Linux systems should able to ping each other. Use ping command to check ping.
  • One system should act as Server and other system should act as client at one particular time.

Limitations:

Before we proceed further we should know that there are some limitations of this program.

  • Python3+ should be installed to run this program. You may observe error or different behavior if run on python older versions.
  • Only text file can be transferred through this program as of now. Any other format file which does not contain text may fail.
  • Basic programming exceptions have been handled in the program.
  • Program may or may not run on other OS than Ubuntu.
  • Text file should be short at client side as buffer size of 1024 bytes has been used.

Set up requirements:

  • We need at least one Linux system to try out this program. But recommendation is to use two different Linux systems which are connected through network.
  • Two systems should be connected through Ethernet or Wi-Fi or any other connections.

Server Source Code:

Client Source Code:

# Importing libraries
import socket
import sys

# Lets catch the 1st argument as server ip
if ( len ( sys . argv ) > 1 ) :
ServerIp = sys . argv [ 1 ]
else :
print ( » \n \n Run like \n python3 client.py \n \n » )
exit ( 1 )

# Now we can create socket object
s = socket . socket ( )

# Lets choose one port and connect to that port
PORT = 9898

# Lets connect to that port where server may be running
s. connect ( ( ServerIp , PORT ) )

# We can send file sample.txt
file = open ( «sample.txt» , «rb» )
SendData = file . read ( 1024 )

while SendData:
# Now we can receive data from server
print ( » \n \n ################## Below message is received from server ################## \n \n » , s. recv ( 1024 ) . decode ( «utf-8» ) )
#Now send the content of sample.txt to server
s. send ( SendData )
SendData = file . read ( 1024 )

# Close the connection from client side
s. close ( )

How to run programs and expected output:

Here are the steps to execute the program.

Step1: Go to B_server system and open a terminal. Short cut to open a terminal is Alt+Ctrl+t.

Step2: Now go the path where server.py is present.

Step3: Now run server.py like below

There should not be any errors and you should see below prints

Copied file name will be recv.txt at server side

Step4: Now open terminal at A_client system.

Step5: Go to the path where client.py and sample.txt are present.

Step6: Now run client.py like below

We have observed that we need to know the IP address of server. We can execute below command to know the IP address of B_server system.

Now output of A_client system should be like this

Step7: Now go to B_server and look for below output

Step8: There should be one file name recv.txt at server folder. The content of this recv.txt should be same sample.txt.

So we have successfully copied a file from client to server over network through python program.

Code explanations:

There are two python files server.py and client.py.

Note that we will explain once if any code is same inside server.py and client.py.

This is shebang line which means by default this server.py should use python3. Let’s see one advantage of this line.

We have executed the server.py or client.py like python3 . Now without using python3 we can execute the python file. Follow below commands

Give all permission to .py file:

Источник

Читайте также:  Inner class java это
Оцените статью