I have already talked about the python implementation code of large file transmission under the UDP protocol a few days ago, and today I will implement the python implementation code of large file transmission under the TCP protocol.
The realization process of TCP and UDP is quite different.
**Implementation code: **
Server:
import socket
import time
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')while received_size < file_total_size:
data = sock.recv(1024)
f.write(data)
received_size +=len(data)print('Received',received_size,' Byte')
data = sock.recv(1024)if data == b'end':break
f.close()
s.close()
Client:
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 connection:
s.connect(('127.0.0.1',9999))while True:if count ==0:
s.send(filesize.encode())
start = time.time()
s.recv(1024)
s.send(fname2.encode())for line in f:
s.send(line)print('sending...')
s.send(b'end')break
s.close
end = time.time()print('cost'+str(round(end - start,2))+'s')
Run screenshot:
Service-Terminal:
Client:
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts