python uses socket to realize udp file transfer function

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

In this paper, we share the specific code of UDP to realize file transmission for your reference, the specific contents are as follows

tcp for file transfer look here-python for TCP file sending and receiving

Here the receiver 1 directly received, the sender each time to send a file, convenient for me in other functions to call the send file.

Using udp is prone to packet loss and needs to be dealt with

Note that tcp and udp have different sockets


# udp:
udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# tcp
tcp_socketr = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 

1. Send


# import socket
# import tqdm
# import os
# import threading
#
# #  Data and files are transmitted from the client to the server 

import threading
import socket
import tqdm
import os
import cv2
from time import ctime, sleep

def send(address, filename):

    #  Transmission data spacer 
    SEPARATOR = '<SEPARATOR>'
    #  Server information 
    host, port = address

    #  File buffer 
    Buffersize = 4096*10
    #  Transfer file name 
    filename = filename
    #  File size )
    file_size = os.path.getsize(filename)
    #  Create socket Link 
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    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.sendto(f'{filename}{SEPARATOR}{file_size}'.encode(), ("127.0.0.1", 1234))
    s.send(f'{filename}{SEPARATOR}{file_size}'.encode('utf-8'))

    #  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)
            # print(bytes_read)
            if not bytes_read:
                print('exit Exit transmission, transmission is complete! ')
                s.sendall('file_download_exit'.encode('utf-8'))
                break
            # sendall  Ensure that data can still be transmitted when the network is busy 
            s.sendall(bytes_read)
            progress.update(len(bytes_read))
            sleep(0.001)

    #  Close resources 
    s.close()


if __name__ == '__main__':
    address = ('127.0.0.1', 1234)
    # host = '127.0.0.1'
    # port = 1234
    filename = input(' Please enter a file name: ')
    t = threading.Thread(target=send, args=(address, filename))
    t.start()
    # received(address, filename)

2. Receive


import socket
import tqdm
import os
import threading

#  Use UDP Transmit video, full duplex, but only need 1 Square connection, 1 Just receive it 

#  Set the server's ip And  port
#  Server information 
# sever_host = '127.0.0.1'
# sever_port =1234

def recvived(address, port):

    #  Transmission data spacer 
    SEPARATOR = '<SEPARATOR>'
    #  File buffer 
    Buffersize = 4096*10

    while True:
        print(' Prepare to receive new files ...')

        udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        udp_socket.bind((address, port))
        recv_data = udp_socket.recvfrom(Buffersize)
        recv_file_info = recv_data[0].decode('utf-8')  #  Storing the received data , Filename 
        print(f' Received file information {recv_file_info}')
        c_address = recv_data[1]  #  Store the address information of the customer 
        #  Print client ip
        print(f' Client {c_address} Connect ')
        # recv_data = udp_socket.recv()
        #  Receive client information 
        # received = udp_socket.recvfrom(Buffersize).decode()
        filename ,file_size = recv_file_info.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 = udp_socket.recv(Buffersize)
                #  If there is no data transfer content 
                # print(bytes_read)
                if bytes_read == b'file_download_exit':
                    print(' Complete transmission! ')
                    print(bytes_read)
                    break
                #  Read and write 
                f.write(bytes_read)
                #  Update progress bar 
                progress.update(len(bytes_read))
        udp_socket.close()

if __name__ == '__main__':

    # address = ("127.0.0.1", 1234)
    port = 1234
    address = "127.0.0.1"
    t = threading.Thread(target=recvived, args=(address, port))
    t.start()
    # send(address)

Related articles: