python文件粉碎传输_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"开始传输文件内容")

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()

服务端效果:

客户端效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值