首页 > 编程 > Python > 正文

python:socket传输大文件示例

2019-11-25 16:23:58
字体:
来源:转载
供稿:网友

文件可以传输,但是对比传输前后的文件:socket_test.txt,末尾有一些不一致服务端代码:

#!/usr/bin/python# -*- coding: utf-8 -*-import sysreload(sys)sys.setdefaultencoding("utf-8")import time'''等待连接等待发送文件读取数据写入文件并且保存等待连接'''import socketimport threadingimport timeimport structdef function(newsock, address):  FILEINFO_SIZE = struct.calcsize('128sI')  '''定义文件信息(包含文件名和文件大小)大小。128s代表128个char[](文件名),I代表一个integer or long(文件大小)'''  while 1:    try:      fhead = newsock.recv(FILEINFO_SIZE)      filename, filesize = struct.unpack('128sI', fhead)      '''把接收到的数据库进行解包,按照打包规则128sI'''      print "address is: ", address      print filename, len(filename), type(filename)      print filesize      #filename = 'new_'+filename.strip('/00') # 命名新文件new_传送的文件      filename = filename.strip('/00')      fp = open(filename, 'wb') # 新建文件,并且准备写入      restsize = filesize      print "recving..."      while 1:        if restsize > 102400: # 如果剩余数据包大于1024,就去1024的数据包          filedata = newsock.recv(10240)        else:          filedata = newsock.recv(restsize)          fp.write(filedata)          #break        if not filedata:          break        fp.write(filedata)        restsize = restsize - len(filedata) # 计算剩余数据包大小        if restsize <= 0:          break      fp.close()      print "recv succeeded !!File named:", filename    except Exception, e:      print unicode(e).encode('gbk')      print "the socket partner maybe closed"      newsock.close()      breaksock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建tcp连接sock.bind(('10.240.146.82', 8887)) # 定于端口和ipsock.listen(5) # 监听while True:  newsock, address = sock.accept()  print "accept another connection"  tmpThread = threading.Thread(target=function, args=(newsock, address)) # 如果接收到文件,创建线程  tmpThread.start() # 执行线程print 'end'

客户端代码:

#!/usr/bin/python# -*- coding: utf-8 -*-import sysreload(sys)sys.setdefaultencoding("utf-8")'''输入文件名,并且上传'''import socketimport timeimport structimport osf = open('socket_test.txt', 'wb')for i in range(1000000):  f.write('for socket test, the line number is : ' + str(i) + '/n')f.close()sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.settimeout(50)e = 0try:  sock.connect(('10.240.146.82', 8887))  print 'connect...'except socket.timeout, e:  print 'timeout', eexcept socket.error, e:  print 'error', eexcept e:  print 'any', eif not e:  #while (1):    #filename = raw_input('input your filename------->') # 输入文件名  filename = 'socket_test.txt'  FILEINFO_SIZE = struct.calcsize('128sI') # 编码格式大小  fhead = struct.pack('128sI', filename, os.stat(filename).st_size) # 按照规则进行打包  sock.send(fhead) # 发送文件基本信息数据  fp = open(filename, 'rb')  fp2 = open('local_test.txt','wb')  i = 0  while 1: # 发送文件    filedata = fp.read(10240)    if not filedata:      break    sock.sendall(filedata)    fp2.write(filedata)    print i    i = i + 1  print "sending over..."  fp.close()  fp2.close()

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表