TCP协议实现切换目录

服务器代码

import socket
import os
import json
import struct

sk = socket.socket()
sk.bind(("127.0.0.1",8888))
sk.listen()
conn, addr = sk.accept()
while 1:

b_len_str_dic = conn.recv(4)
len_dic = struct.unpack("i",b_len_str_dic)[0]
str_r = conn.recv(len_dic).decode("utf-8")
r = json.loads(str_r)
if r["operation"]=="..":
s = os.listdir(os.path.split(r["route"])[0])

ss = json.dumps(s)
conn.send(ss.encode("utf-8"))
if "cd" in r["operation"] :
f = r["operation"].split(" ")[1]
if os.path.isdir(r["route"]+"\\"+f):
ss = os.listdir(r["route"]+"\\"+f)
ss = json.dumps(ss)
conn.send(ss.encode())
else:
ss = f
ss = json.dumps(ss)
conn.send(ss.encode())
if r["operation"] == "3":
break

conn.close()
sk.close()

  客户端代码

import socket
import os
import json
import struct

sk = socket.socket()
sk.connect(("127.0.0.1",8888))
s = input("输入查询文件的绝对路径:")
s = os.sep.join(s.split("\\"))
s = os.path.dirname(s)
print(os.listdir(s))
print("""..,返回上一层目录
cd,进入指定目录
3,退出""")
while 1:
    ss = input("输入要进行的操作:")
    dic = {"route":s,"operation":ss}
    str_dic = json.dumps(dic)
    len_str_dic = len(str_dic)
    b_len_str_dic = struct.pack("i",len_str_dic)
    sk.send(b_len_str_dic + str_dic.encode("utf-8"))
    if ss == "..":
        s = os.path.split(s)[0]
    if "cd" in ss:
        s = s+"\\" + ss.split(" ")[1]
    if ss =="3":
        break
    r = sk.recv(10240).decode("utf-8")
    r1 = json.loads(r)
    print(r1)
sk.close()

  

posted on 2018-08-16 17:35  你们都厉害  阅读(221)  评论(0编辑  收藏  举报