import socket
import os
sk=socket.socket()
print(sk)
address=('127.0.0.1',8000)
sk.bind(address) #将本地地址与一个socket绑定在一起
sk.listen(3) #最多允许有3个客户称呼
print('waiting........ ')
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) #26:11,当前目录
while 1:
conn,addr = sk.accept()
while 1:
# client = conn
data = conn.recv(1024) #缓冲区大小,接收文件的个数 第一次获取请求
# client.send("HTTP/1.1 200 OK\r\n\r\n".encode("utf8"))
# client.send("Hello,yuan
".encode("utf8"))
cmd,filename,filesize=str(data,'utf8').split('|') #第一次提取请求信息,获取 post name size
#filesize = os.stat(data)
path = os.path.join(BASE_DIR,'MNIST_80',filename)
filesize=int(filesize)
f = open(path,'ab')
has_receive=0
while has_receive!=filesize:
data=conn.recv(1024) #第二次获取请求,这次获取的就是传递的具体内容了,1024为文件发送的单位
f.write(data)
has_receive+=len(data)
f.close()
import socket
import os
sk = socket.socket()
print(sk)
address=('127.0.0.1',8000)
sk.connect(address)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
while True:
inp=input('>>>>>>>>') #post|11.png
cmd,path=inp.split('|') #拿到post,以及文件11.jpg
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) #split获取字符串的信息 以此方式打包,依次为 cmd/name/size
sk.sendall(bytes(file_info,'utf8')) #第一次发送请求,不是具体内容,而是先发送数据信息
f = open(path,'rb')
has_sent=0
while has_sent!=file_size:
data = f.read(1024)
sk.sendall(data) #发送真实数据
has_sent+=len(data)
f.close()
print('上传成功')
下面是我,修改的更为简单的socket服务器。。
import socket
import os
sk=socket.socket()
print(sk)
address=('127.0.0.1',8000)
sk.bind(address) #将本地地址与一个socket绑定在一起
sk.listen(3) #最多允许有3个客户称呼
print('waiting........ ')
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) #26:11,当前目录
while 1:
conn,addr = sk.accept()
while 1:
filename = '123456789.jpg'
path = os.path.join(BASE_DIR,'MNIST_80',filename)
f = open(path,'ab')
data=conn.recv(50000)
f.write(data)
f.close()
print(data) #图片数据
#print(type(data))