enter image description here enter image description here
我无法在客户端文件的当前目录下显示该文件。 并显示客户端文件当前目录下的所有目录和子目录。
我应该像上面的图片一样在客户端的命令提示符中显示它。
请帮助我提供此代码。谢谢
到目前为止,这是我拥有的代码:
server.py:
import socket
import threading
import os
HOST = "localhost"
PORT = 5551
def setpath(curdir, np, conn):
print("setting new path")
print("from: ", curdir)
print("to: " , np)
m = "New Path: " + np
conn.send(m.encode('utf-8'))
def showfiles(p, conn):
ffound = "Files found under: " + p + "\n"
conn.send(ffound.encode('utf-8'))
for (path, dirlist, filelist) in os.walk(p):
for f in filelist:
print(f)
f = f + "\n"
conn.send(f.encode('utf-8'))
def showdir(p, conn):
dfound = "Directories found under: " + p + "\n"
conn.send(dfound.encode('utf-8'))
for (path, dirlist, filelist) in os.walk(p):
for d in dirlist:
print(os.path.join(path, d))
dr = os.path.join(path, d) + "\n"
conn.send(dr.encode('utf-8'))
def clientsocket():
s.listen()
(conn, addr) = s.accept()
FCL = []
while True:
fromClient = conn.recv(1024).decode('utf-8')
FCL.append(fromClient)
if fromClient == 's':
fc = conn.recv(1024).decode('utf-8')
setpath(FCL[0], fc, conn)
FCL.pop()
if fromClient == 'f' :
showfiles(FCL[0], conn)
FCL.pop()
if fromClient == 'd' :
showdir(FCL[0], conn)
FCL.pop()
if fromClient == 'q':
break
with socket.socket() as s :
s.bind((HOST, PORT))
print("Server hostname:", HOST, "port:", PORT)
try :
s.settimeout(10) # set timer to time out after 3 seconds
threads= []
t = threading.Thread(target = clientsocket)
threads.append(t)
t.start()
for th in threads :
th.join()
except socket.timeout :
print("Caught Time-Out! No Client Connected.")
client1.py
import socket
import os
HOST = '127.0.0.1'
PORT = 5551
def userinput(p):
m = input("s: set path \nf: show files \nd: show dirs \nq: quit \nEnter Choice: ")
while m not in ['s','f','d','q']:
m = input("s: set path \nf: show files \nd: show dirs \nq: quit \nEnter Choice: ")
s.send(m.encode('utf-8'))
if m == 's':
newpath= input("Enter path, starting from current directory: ")
s.send(newpath.encode('utf-8'))
return m
def display():
print()
with socket.socket() as s :
s.connect((HOST, PORT))
print("Client connect to:", HOST, "port:", PORT)
p = os.getcwd()
s.send(p.encode('utf-8'))
print("Current Directory:", p)
mesg = userinput(p)
while mesg != 'q':
fromServer = s.recv(1024).decode('utf-8')
print(fromServer)
mesg = userinput(p)