python - 从服务器搜索文件并发送到客户端
问题描述
我想制作一个可以在服务器计算机中搜索文件的程序,如果文件存在于服务器中,则通知客户端,如果它不通知客户端,然后将结果打印到客户端,然后将文件发送到客户端。
这是我的客户端代码
客户端.py
import socket
HOST = '127.0.0.1'
PORT = 2000
def find_all(search):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
search = input("Enter file name: ")
socket1.send(search.encode('utf-8'))
found = socket1.recv(1024).decode('utf-8')
result = socket1.recv(1024).decode('utf-8')
print(result)
not_found = socket1.recv(1024).decode('utf-8')
with open(result, 'wb') as file_to_write:
while True:
result = socket1.recv(1024).decode("utf-8")
print(result)
if not result:
break
file_to_write.write(result.encode('utf-8'))
file_to_write.close()
print('Download Successful')
socket1.close()
return
print(find_all('search'))
这是来自客户端的错误
Traceback (most recent call last):
File "/cient.py", line 29, in <module>
print(find_all('search'))
File "/client.py", line 16, in find_all
with open(result, 'wb') as file_to_write:
FileNotFoundError: [Errno 2] No such file or directory: ''
这是我的服务器端代码:
服务器.py
import socket
import os
from pathlib import Path
HOST = '127.0.0.1'
PORT = 2000
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.bind((HOST, PORT))
socket1.listen(5)
conn, addr = socket1.accept()
result = []
search = conn.recv(1024).decode('utf-8')
path = str(Path.home())
for root, dirs, files in os.walk(path):
if search in files:
found = socket1.send("File found".encode('utf-8'))
print('data=%s', found)
result.append(os.path.join(root, search))
socket1.send(result.encode('utf-8'))
else:
not_found = socket1.send("File not found".encode('utf-8'))
print('data=%s', not_found)
while True:
with open('result', "rb") as file_to_send:
for result in file_to_send:
conn.sendall(result.encode('utf-8'))
print('Send Successful')
这是来自服务器的错误
Traceback (most recent call last):
File "/server.py", line 22, in <module>
not_found = socket1.send("File not found".encode('utf-8'))
BrokenPipeError: [Errno 32] Broken pipe
当我运行这两个代码时,它可以工作,但如果文件不存在或文件夹中确实存在,则不会向客户端显示输出。
解决方案
推荐阅读
- java - 运行并行测试时如何使用 driver.quit()
- python - 如何检查 ssh.exec_command 执行成功与否?
- performance - 使用 jupyter lab 浏览器变得非常慢
- python - UserProfileInfoForm 对象不可调用
- computer-vision - 表单识别器/计算机视觉 pbm 文件支持
- javascript - 使用 Google Maps API 访问嵌套的 geojson 数据
- django - Django中具有起始值的自动增量字段
- python-3.x - 通过不扩展列从字典中制作熊猫数据框 from_dict(df, orient='index') expand = false
- javascript - 有没有办法可以在父函数的子函数中退出父函数?
- jenkins - 在 Jenkins Pipeline 中创建远程存储库和跟踪