实现:client上传图片文件到server
如下图所示,图片与post_client.py在同一当前目录
-------------------post_server.py-----------------------------------------
import subprocess
#subprocess.Popen,主要用Popen这个类实现shell
import os
import socket
sk=socket.socket()
print(sk)
address=('127.0.0.1',8005)
sk.bind(address)
sk.listen(3)
print('waiting.....')
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
while True:
conn,addr = sk.accept()
print(addr)
while True:
data=conn.recv(1024) #接收
cmd,filename,filesize=str(data,'utf-8').split('|') #用三个变量解析接收的并用|分隔
path=os.path.join(BASE_DIR,'yuan','filename') #路径拼接,这里指定在yuan下
filesize=int(filesize)
#循环收
f=open(path,'ab')
has_receive=0
while has_receive!=filesize:
data=conn.recv(1024)
f.write(data)
has_receive+=len(data)
f.close()
--------------------post_client.py------------------------
import socket
import os
sk=socket.socket()
print(sk)
address=('127.0.0.1',8005)
sk.connect(address)
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
while True:
inp=input('>>>').strip() #post|1.png
cmd,path = inp.split('|') #两个变量接收,并用|分隔开
path=os.path.join(BASE_DIR,path) #路径拼接-----绝对路径
filename=os.path.basename(path) #你放参数路径,它会取到最后的文件名字
file_size=os.stat(path).st_size # 看文件大小
file_info='post|%s|%s'%(filename,file_size) #
sk.sendall(bytes(file_info,'utf-8')) #发过去
#循环发
f = open(path, 'rb') # 打开
has_sent=0 #已发的
while has_sent !=file_size:
data=f.read(1024) #每次1024个的一段段发
sk.sendall(data)
has_sent+=len(data)
f.close()
print('上传成功')
sk.close()