# 切换目录(客户端代码)
import socket
import os
sk = socket.socket()
sk.connect(("127.0.0.1",8090))
abs_path = input('请输入一个根目录:')
sk.send(abs_path.encode('utf-8'))
current_dir = sk.recv(1024).decode('utf-8')
print(current_dir.split('--'))
while 1:
cmd = input('请输入指令>>>')
sk.send(cmd.encode('utf-8'))
if cmd.upper() == 'Q': # 退出循环
break
elif cmd == '..':
current_dir = sk.recv(1024).decode('utf-8')
print(current_dir.split('--'))
elif cmd == 'cd':
filename = input('请输入一个文件名>>>')
sk.send(filename.encode('utf--8'))
current_dir = sk.recv(1024).decode('utf-8')
print(current_dir.split('--'))
else:
error = sk.recv(1024).decode('utf-8')
print(error)
# 切换目录(服务器端代码)
import socket
import os
sk = socket.socket()
sk.bind(('127.0.0.1',8090))
sk.listen()
conn,addr = sk.accept()
def send_data(conn,path):
try: # 当文件找不到时会出错,故用try来解决一问题
list_dir = os.listdir(path)
current_dir = '--'.join(list_dir)
conn.send(current_dir.encode('utf-8'))
except FileNotFoundError:
conn.send('系统找不到指定的路径。'.encode('utf-8')) # 文件找不到时返回这个错误
abs_path = conn.recv(1024).decode('utf-8')
current_path = abs_path + '\'
send_data(conn,current_path)
while 1:
cmd = conn.recv(1024).decode('utf-8')
if cmd.upper() == 'Q':
break
elif cmd == '..':
current_dir = current_path.split('\')[:-2]
current_path = '\'.join(current_dir) + '\'
send_data(conn,current_path)
elif cmd == 'cd':
filename = conn.recv(1024).decode('utf-8')
current_path += filename + '\'
send_data(conn,current_path)
else:
conn.send('指令错误'.encode('utf-8'))