技术0
经验241
魅力0
人气5
分享0
原创0
注册时间2022-12-1
最后登录2022-12-2
阅读权限15
在线时间1 小时
主题1
回帖5

初出茅庐

- 积分
- 131
- 人气
- 5
- 分享
- 0
|
自己写的。。。
已知BUG:在Windowd Server 2008上会返回自身,不知道为什么,也没去修,不方便调试(因为我是MAC系统)
# server
import socket
def folder(folder_name):
import os
try:
os.mkdir(folder_name)
except FileExistsError:
# return "文件夹已存在"
return False # 因文件夹已存在而创建失败就返回False
else:
# return "文件夹创建成功"
return True # 创建成功返回True
# 创建UPD服务端套接字
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
# 绑定地址和端口
s.bind(("", 9002))
# 等待接收信息
while True:
# 接收数据和客户端请求地址
data, address = s.recvfrom(1024) # 一次最多发多少包
if not data:
break # data不存在的话就重新循环
import time
print("[{}:{} {}]:{}".format(str(address[0]), str(address[1]), time.strftime("%Y/%m/%d %H:%M:%S"),
data.decode("utf-8")))
import os
if folder("py") == True:
print("你没有文件夹,已新建一个名为py的文件夹,请把程序放入并把文件名改为1.py或2.py之类的")
if data.decode("utf-8").split("|")[1] == "文件":
file_name = "./py/" + data.decode("utf-8").split("|")[0] + ".py"
if os.path.isfile("./py/" + data.decode("utf-8").split("|")[0] + ".py") == False:
s.sendto("文件不存在".encode("utf-8"), address)
break
else:
with open(file_name, "r", encoding="utf-8") as file:
file_len = str(len(file.readlines())) + "|共?行"
s.sendto(file_len.encode("utf-8"), address)
import time
folder("log")
File_Name = "./log/" + time.strftime("%Y-%m-%d") + ".txt" # 按天来记录log
with open(File_Name, "a+", encoding="utf-8") as file:
file.write(
"{}:{} 在 {} 访问 {}.py\n".format(str(address[0]), str(address[1]), time.strftime("%H:%M:%S"),
data.decode("utf-8").split("|")[0]))
elif data.decode("utf-8").split("|")[1] == "第?行":
import linecache
file_name = "./py/" + data.decode("utf-8").split("|")[2]
file_data = linecache.getline(file_name, int(data.decode("utf-8").split("|")[0]))
s.sendto(file_data.encode("utf-8"), address)
s.close()
# client
import socket
# Host = "8.131.94.236"
Host = "localhost"
Port = 9002
BUFFSIZE = 1024
# from time import ctime
# 创建客户端套接字
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
while True:
# 发送信息到服务器 data.decode("utf-8").split("|")[0] + ".py"
file_name = input("请输入你要获取得文件:") # 可以直接file_name = "1",会直接获取“1.py”,就做到远程更新了
data = file_name + "|文件"
# data = '[{}]:{}'.format(ctime(), data)
s.sendto(data.encode("utf-8"), (Host, Port))
# 接收服务端返回信息
recvData, addrs = s.recvfrom(BUFFSIZE)
if recvData.decode("utf-8").split("|")[0] == "文件不存在":
print("文件不存在")
print("获取成功~")
print("共有" + recvData.decode("utf-8").split("|")[0] + "行")
if recvData.decode("utf-8").split("|")[1] == "共?行":
file_line = recvData.decode("utf-8").split("|")[0]
for i in range(int(recvData.decode("utf-8").split("|")[0])):
line = str(i + 1) + "|第?行|" + file_name + ".py"
s.sendto(line.encode("utf-8"), (Host, Port))
recvData, addrs = s.recvfrom(BUFFSIZE) # 接收服务端返回信息
with open("./" + file_name + ".py", "a+", encoding="utf-8") as file:
file.write(recvData.decode("utf-8") + "\n")
import os
# os.system("python ./" + file_name + ".py")
else:
print(recvData.decode("utf-8"))
# 关闭套接字
s.close()
|
评分
-
查看全部评分
|