上传已经ok,下载是一样的
#server
# import socket
# sk=socket.socket()
# sk.bind(('127.0.0.1',9000))
# sk.listen()
# import json,os
#
# conn,addr=sk.accept()
# msg=conn.recv(4)
# length=struct.unpack('i',msg)
# key=conn.recv(length[0])
# li=json.loads(key.decode('utf-8'))
# print(li)
# ret=False
# if li[0]=='zlz' and li[1]=='666':
# result='登录成功'
# length=struct.pack('i',len(result.encode('utf-8')))
# conn.send(length)
# conn.send(result.encode('utf-8'))
# ret=True
# else:
# result='登录失败'
# length = struct.pack('i', len(result.encode('utf-8')))
# conn.send(length)
# conn.send(result.encode('utf-8'))
import socketserver
import struct
import json
import os
class Myserver(socketserver.BaseRequestHandler):
def handle(self):
conn = self.request
while True:
try:
msg = conn.recv(4)
length = struct.unpack('i', msg)
key = conn.recv(length[0])
li = json.loads(key.decode('utf-8'))
print(li)
ret = False
if li[0] == 'zlz' and li[1] == '666':
result = '登录成功'
length = struct.pack('i', len(result.encode('utf-8')))
conn.send(length)
conn.send(result.encode('utf-8'))
ret = True
else:
result = '登录失败'
length = struct.pack('i', len(result.encode('utf-8')))
conn.send(length)
conn.send(result.encode('utf-8'))
if ret:
result = '选择 上传文件 下载文件'
length = struct.pack('i', len(result.encode('utf-8')))
conn.send(length)
conn.send(result.encode('utf-8'))
msg = conn.recv(4)
length = struct.unpack('i', msg)
key = conn.recv(length[0])
li = key.decode('utf-8')
print(li)
msg = conn.recv(4)
length = struct.unpack('i', msg)[0]
print(length)
if li=='上传文件':
with open(r'C:\Users\lenovo\Desktop\339.tif',mode='wb') as f:
while length>0:
ret = conn.recv(1024)
f.write(ret)
length -= len(ret)
print('finish')
break
except ConnectionResetError:
break
conn.close()
server = socketserver.ThreadingTCPServer(('127.0.0.1',9001),Myserver)
server.serve_forever()
#client
import socket
sk=socket.socket()
import struct
sk.connect(('127.0.0.1',9001))
import sys
import os
import json
class User:
def __init__(self,account,pwd):
self.acconut = account
self.pwd = pwd
self.info = [self.acconut, self.pwd]
key = json.dumps(self.info).encode('utf-8')
length = len(key)
l=struct.pack('i', length)
sk.send(l)
sk.send(key)
while True:
account=input('输入账号')
pwd=input('输入密码')
a=User(account,pwd)
msg=sk.recv(4)
length=struct.unpack('i',msg)[0]
msg=sk.recv(length)
print(msg.decode('utf-8'))
msg = sk.recv(4)
length = struct.unpack('i', msg)[0]
msg = sk.recv(length)
print(msg.decode('utf-8'))
result=input('输入您的操作')
length = struct.pack('i', len(result.encode('utf-8')))
sk.send(length)
sk.send(result.encode('utf-8'))
path=input('path>>>')
filesize=os.path.getsize(path)
length = struct.pack('i', filesize)
print(length)
sk.send(length)
with open(path,mode='rb') as f:
while filesize>0:
content=f.read(1024)
sk.send(content)
filesize-=1024
sk.close()
# r'C:\Users\lenovo\Desktop\239.tif'