python Realizes TCP File Receiving and Sending

  • 2021-11-29 07:34:39
  • OfStack

This article example for everyone to share python implementation of TCP file receiving and sending specific code, for your reference, the specific content is as follows

Share the next article: Implementation of udp transceiver

First, run the server side to open the receiving, and send the file at the running customer service side

And remember to change ip for 1 time

1. Send

Modify according to your own needs, and complete file sending and receiving under simple LAN

Client


#  Data and files are transmitted from the client to the server 

import socket
import tqdm
import os


def send(filename):
    #  Transmission data spacer 
    SEPARATOR = '<SEPARATOR>'
    #  Server information 
    host = '127.0.0.1'
    port =1234
    #  File buffer 
    Buffersize = 4096*10
    #  Transfer file name 
    filename = filename
    #  File size 
    file_size  = os.path.getsize(filename)
    #  Create socket Link 
    s = socket.socket()
    print(f' Server connection {host}:{port}')
    s.connect((host, port))
    print(' Successful connection to server ')

    #  Send file name and file size, which must be encoded 
    s.send(f'{filename}{SEPARATOR}{file_size}'.encode())

    #  File transfer 
    progress = tqdm.tqdm(range(file_size), f' Send {filename}', unit='B', unit_divisor=1024)

    with open(filename,'rb') as f :
        #  Read a file 
        for _ in progress:
            bytes_read = f.read(Buffersize)
            if not bytes_read:
                break
            # sendall  Ensure that data can still be transmitted when the network is busy 
            s.sendall(bytes_read)
            progress.update(len(bytes_read))
    #  Close resources 
    s.close()

if __name__ == '__main__':
    filename = input(' Please enter a file name: ')
    send(filename)

2. Receive

Server side


import socket
import tqdm
import os
import threading

def received():
    #  Set the server's ip And  port
    #  Server information 
    sever_host = '127.0.0.1'
    sever_port =1234
    #  Transmission data spacer 
    SEPARATOR = '<SEPARATOR>'

    #  File buffer 
    Buffersize = 4096*10
    s = socket.socket()
    s.bind((sever_host, sever_port))

    #  Set the number of listeners 
    s.listen(128)
    print(f' Server listening {sever_host}:{sever_port}')

    #  Receive client connection 
    client_socket, address = s.accept()
    #  Print client ip
    print(f' Client {address} Connect ')

    #  Receive client information 
    received = client_socket.recv(Buffersize).decode()
    filename ,file_size = received.split(SEPARATOR)
    #  Get the name of the file , Size 
    filename = os.path.basename(filename)
    file_size = int(file_size)

    #  File receiving processing 
    progress = tqdm.tqdm(range(file_size), f' Receive {filename}', unit='B', unit_divisor=1024, unit_scale=True)


    with open('8_18_'+filename,'wb') as f:
        for _ in progress:

            #  Read data from the client 
            bytes_read = client_socket.recv(Buffersize)
            #  If there is no data transfer content 
            if not bytes_read:
                break
            #  Read and write 
            f.write(bytes_read)
            #  Update progress bar 
            progress.update(len(bytes_read))

    #  Close resources 
    client_socket.close()
    s.close()

if __name__ == '__main__':
    received()

Related articles: