我想制作一个程序,可以在服务器的计算机中搜索文件,如果服务器中存在该文件,则通知客户端(如果未通知客户端),然后将结果打印到客户端,然后将文件发送至客户。
这是我的客户端代码
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: ''
这是我的服务器端代码:
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
当我同时运行这两个代码时,它可以工作,但不能运行;如果文件不存在或文件夹中不存在,则不会将输出显示给客户端。