• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python基于stuck实现scoket文件传输

python 搞代码 4年前 (2022-01-07) 16次浏览 已收录 0个评论

这篇文章主要介绍了Python基于stuck实现scoket文件传输,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

使用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"开始传输文件内容") whi<strong style="color:transparent">来源gao@daima#com搞(%代@#码网</strong>le 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()

客户端效果

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

以上就是Python基于stuck实现scoket文件传输的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python基于stuck实现scoket文件传输

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址