不多说,第一次发,直接上代码。
cs 架构
服务端代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket,time,SocketServer,struct,os,threading
host='192.168.9.184'
port=12345
basepath='/root/'
buffersize=1024
timeout=1200
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(100)
print('等待客户端连接...')
def acceptClient(sock, addr):
print('已经有客户端[%s:%s]连接上' % addr)
st = struct.Struct('>128sQ')
try :
sock.settimeout(timeout)
prebuffer = sock.recv(st.size)
filename,filesize=st.unpack_from(prebuffer,0)
filename_f = filename.strip('\00')
filenewname = os.path.join(basepath,('new_'+filename_f))
with open(filenewname,'wb') as f :
while True:
data = sock.recv(buffersize)
if not data :
break
f.write(data)
print('[%s]文件已经上传成功!' % filenewname)
except Exception as e :
print("Error:",e)
finally :
sock.close()
print('[%s:%s]连接已经关闭!' % addr)
#死循环接收客户端连接
while True:
sock, addr = s.accept()
t = threading.Thread(target=acceptClient, args=(sock, addr))
t.start()
客户端代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket,os,struct,ctypes,sys
from sys import argv
if len(argv)!=2 :
print("Usage:"+argv[0]+" filename")
exit()
if not os.path.isfile(argv[1]) :
print("Error: filename must exits!!!")
exit()
host='192.168.9.184'
port=12345
buffersize=1024
timeout=1200
#简单实现进度条,如果要看到效果请选一个几百MB的文件。
def progressbar(f,x,maxStep=100):
xPercent = int(0.1 * x / maxStep * 1000)
sys.stdout.write("\r")
sys.stdout.write("["+f+"][")
for m in range(0,x):
sys.stdout.write('-')
if x == 0 :
sys.stdout.write('=')
elif x < maxStep:
sys.stdout.write('>')
else :
sys.stdout.write('-')
for n in range(x,maxStep):
sys.stdout.write('=')
sys.stdout.write("]["+str(xPercent)+"%]")
#sys.stdout.write("\r")
sys.stdout.flush()
filename=argv[1]
st = struct.Struct('>128sQ')
prebuffer = ctypes.create_string_buffer(st.size)
basefilename = os.path.basename(filename)
totalsize = os.stat(filename).st_size
tp=(basefilename,totalsize)
st.pack_into(prebuffer,0,*tp)
#输出进度条
def doprogressbar(index,maxStep=100) :
xStep=1
if buffersize >= totalsize :
xStep=step
else :
xStep = int(0.1 * maxStep * index * buffersize / totalsize * 10)
progressbar(basefilename,xStep,maxStep)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try :
s.settimeout(timeout)
s.connect((host,port))
#先发送带文件名和文件大小的struct数据。
s.send(prebuffer)
#再打开文件循环发送文件数据并打印进度条
with open(filename,'rb') as f :
index=0
while True :
data = f.read(buffersize)
if not data :
break
s.send(data)
index += 1
doprogressbar(index,60)
print("")
print('[%s]文件已经发送完毕' % basefilename)
except Exception as e:
print("Error:",e)
finally :
s.close()
注意:简单修改ip,端口,就可以运行!!!