socket编程

TCP/UDP协议

Posted by Zhao Zihao on December 26, 2020

使用TCP协议和UDP协议,实现本地Client端和Server端的文件传输,文件可以是大文件,图片,也可以是视频文件等

使用TCP协议进行文件传输

Server端:

# -*- coding=utf-8 -*-
import socket
import time

count = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9999))
s.listen(5)
print('Waiting for connection...')

while True:
    sock, addr = s.accept()
    print('Accept new connection from %s:%s...' % addr)
    if count == 0:
        data1 = sock.recv(1024)
        print(str(data1))
        file_total_size = int(data1.decode())
        received_size = 0
        sock.send('received'.encode())
        data = sock.recv(1024)
        filepath = str(data.decode())
        f = open(filepath, 'wb')
        start = time.time()
    while received_size < file_total_size:
        data = sock.recv(1024)
        f.write(data)
        received_size += len(data)
        # Count the system time after each iteration
        end = time.time()
        # If 1s is run,print the current time and the current cumulative number of transfers
        if end - start > 1:
            print(end)
            print('Accept ', received_size, ' B')
            start = time.time()
    data = sock.recv(1024)
    if data == b'end':
        break
print(end-start)

Client端:

# -*- coding=utf-8 -*-
import socket
import os
import time

filename = input('please enter the filename you want to send:\n')
filesize = str(os.path.getsize(filename))
fname1, fname2 = os.path.split(filename)
client_addr = ('127.0.0.1',9999)
f = open(filename,'rb')
# count = 0
# flag = 1
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Establish a connection:
s.connect(('127.0.0.1', 9999))
while True:
    # if count == 0:
    s.send(filesize.encode())
    start = time.time()
    current_start = time.time()
    s.recv(1024)
    s.send(fname2.encode())
    for line in f:
        s.send(line)
        # Statistics the current system running time
        current_end = time.time()
        # If 1s is run, the current time of printing is used as one of the coefficients of the end-to-end delay
        if current_end-current_start >1:
            print(current_end)
            current_start = time.time()
    s.send(b'end')
    break

s.close
end = time.time()
print('cost ' + str(round(end - start, 6)) + 's')

使用UDP协议进行文件传输

Server端:

# -*- coding=utf-8 -*-
import socket
import time
count = 0
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_addr = ('127.0.0.1',9999)
s.bind(server_addr)

print('Bind UDP....')

received_size = 0
while True:
    if count == 0:
        data,client_addr = s.recvfrom(4096)
        print('connected from %s:%s'%client_addr)
        # Record the start time of the receiver running
        start = time.time()
        f = open(data, 'wb')
    data, client_addr = s.recvfrom(4096)
    if str(data) != "b'end'":
        received_size += len(data)
        f.write(data)
        # Record the current system time
        end = time.time()
        # Print the current time every 1s while printing the cumulative amount of transmission
        if end-start>1:
            print(end)
            print('Accept ', received_size, ' B')
            start = time.time()
    else:
        break
    s.sendto('ok'.encode('utf-8'),client_addr)
    count+=1
print('total received ',received_size, ' B')
f.close()
s.close()

Client端:

# -*- coding=utf-8 -*-
import socket
import os
import time

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

filename = input('please enter the filename you want to send:\n')
filesize = str(os.path.getsize(filename))
fname1, fname2 = os.path.split(filename)

client_addr = ('127.0.0.1',9999)
f = open(filename,'rb')
count = 0
# flag = 1
while True:
    if count == 0:
        data = bytes(fname2, encoding = "utf8")
        # The start time of the sending end is recorded,which is used to calculate the total running time and 1s respectively
        total_start = time.time()
        current_start = time.time()
        s.sendto(data,client_addr)
    data = f.read(4096)
    if str(data) != "b''":
        s.sendto(data,client_addr)
    else:
        s.sendto('end'.encode('utf-8'),client_addr)
        break
    current_end = time.time()
    # Print the timestamp of the sending end for every 1s
    if current_end-current_start>1:
        print(current_end)
        current_start = time.time()
    data, server_addr = s.recvfrom(4096)
    count+=1

s.close
total_end = time.time()
print('total cost: '+str(round(total_end-total_start,6))+'s')