Python基于stuck实现scoket文件传输
2020-04-03 12:04
531 查看
使用socket中的struck来实现客户端发送
服务端:
客户端:
# -*- coding: UTF-8 -*- import socket, time, socketserver, struct, os, _thread host = '127.0.0.1' port = 12307 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定义socket类型 s.bind((host, port)) # 绑定需要监听的Ip和端口号,tuple格式 s.listen(1) def conn_thread(connection, address): while True: try: connection.settimeout(600) fileinfo_size = struct.calcsize('12sl')#12s表示12个字符,l表示一个长整型数 buf = connection.recv(fileinfo_size) if buf: # 如果不加这个if,第一个文件传输完成后会自动走到下一句,需要拿到文件大小信息才可以继续执行 filename, filesize = struct.unpack('12sl', buf) filename_f = filename.decode("utf-8").strip('\00') # C语言中'\0'是一个ASCII码为0的字符,在python中表示占一个位置得空字符 filenewname = os.path.join('e:\\', os.path.basename(filename_f)) print(u'文件名称:%s , 文件大小: %s' % (filenewname, filesize)) recvd_size = 0 # 定义接收了的文件大小 file = open(filenewname, 'wb') print(u"开始传输文件内容") while not recvd_size == filesize: if filesize - recvd_size > 1024: rdata = connection.recv(1024) recvd_size += len(rdata) else: rdata = connection.recv(filesize - recvd_size) recvd_size = filesize file.write(rdata) file.close() print('receive done') # connection.close() except socket.timeout: connection.close() while True: print(u"开始进入监听状态") connection, address = s.accept() print('Connected by ', address) # thread = threading.Thread(target=conn_thread,args=(connection,address)) #使用threading也可以 # thread.start() _thread.start_new_thread(conn_thread, (connection, address)) s.close()
服务端效果:
# -*- coding: UTF-8 -*- import socket, os, struct s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 12307)) while True: filepath = input('请输入要传输的文件绝对路径:\r\n') print(type(filepath)) print(len(filepath.encode("utf-8"))) if os.path.isfile(filepath): #fileinfo_size = struct.calcsize('20sl') # 定义打包规则 # 定义文件头信息,包含文件名和文件大小 fhead = struct.pack('12sl', filepath.encode("utf-8"), os.stat(filepath).st_size) print(os.stat(filepath).st_size) s.send(fhead) print (u'文件路径: ', filepath) # with open(filepath,'rb') as fo: 这样发送文件有问题,发送完成后还会发一些东西过去 fo = open(filepath, 'rb') while True: filedata = fo.read(1024) if not filedata: break s.send(filedata) fo.close() print (u'传输成功') # s.close()
客户端效果
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- python3.5基于TCP实现文件传输
- 基于python的分词算法的实现(1) - 算法
- 基于python的分词算法的实现(2) - 字典的选择
- Python实现基于HTTP文件传输实例
- 基于XML和Python实现白盒测试程序与测试用例分离
- 在安卓下控制基于树莓派的小车 皆用python实现
- Python实现的基于ADB的Android远程工具
- Python实现的基于ADB的Android远程工具
- 基于随机游走的社团划分算法label progation 的python实现
- python实现基于ssh的分发器
- Python3.2 实现基于KNN算法的数据分类
- Python基于twisted实现简单的web服务器
- 基于朴素贝叶斯的关于互联网金融新闻分类(python实现)
- Python 使用循环数组实现队列 (基于class, 包含迭代器)
- 基于物品的协同过滤算法和SlopeOne的python实现
- python 基于XML生成静态网页的简单实现
- 用Python实现基于依赖关系的排序
- python实现基于CGI的Web应用
- 能分析压缩的日志,且基于文件输入的PYTHON代码实现
- Photoshop中磁力套索的一种简陋实现(基于Python)