DDR爱好者之家 Design By 杰米

前几天已经讲过了UDP协议下大文件传输的python实现代码,今天再实现TCP协议下大文件传输的python实现代码。
TCP和UDP的实现过程还是比较不一样的。

实现代码:

服务端:

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_size,' Byte')
 data = sock.recv(1024)
 if data == b'end':
  break
  
f.close()
s.close()

客户端:

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)
#建立连接:
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')

运行截图:

服务器端:

python实现TCP文件传输

客户端:

python实现TCP文件传输

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米