使用Socket 传送一个文件

服务端定义一个传输内容得规则,然后客户端按照此内容进行传输,服务端按照此内容进行解析。

服务端


#encoding=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)

s.bind((host,port))

s.listen(1)


def conn_thread(connection,address):

while True:

try:

connection.settimeout(600)

fileinfo_size = struct.calcsize("12sl")

buf = connection.recv(fileinfo_size)

if buf:

filename,filesize = struct.unpack("12sl",buf)#接收到数据解析为一个字符串和一个长整形数

filename_f = filename.decode("utf-8").strip("\00")

 filenewname = os.path.join("e:\\",os.path.basename(filename_f))

print("文件名称: %s 文件大小: %s" %(filenewname,filesize))

recvd_size = 0

file = open(filenewname,"wb")

print("开始传输文件内容")

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

except socket.timeout:

connection.close()



while True:

print("开始进入监听状态")

connection,address = s.accept()

print("Connected by ",address)

_thread.start_new_thread(conn_thread,(connection,address))  

s.close()

客户端

#encoding=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("Please Enter chars:\r\n")

print(type(filepath))

print(len(filepath.encode("utf-8")))

if os.path.isfile(filepath):

fhead = struct.pack("12sl",filepath.encode("utf-8"),os.stat(filepath).st_size)

print(os.stat(filepath).st_size)

s.send(fhead)

print("文件路径:",filepath)

fo = open(filepath,"rb")

while True:

filedata = fo.read(1024)

if not filedata:

break

s.send(filedata)

fo.close()

print("传输成功")

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容