gpt4 book ai didi

python-3.x - 如何使用Python告诉客户端服务器中不存在文件

转载 作者:行者123 更新时间:2023-12-03 11:58:43 25 4
gpt4 key购买 nike

我正在编写一个简单的客户端服务器简单应用程序,其中客户端向服务器请求某个文件。如果文件存在,则服务器发送文件及其大小;否则,服务器将发送文件。如果不存在,则服务器将向客户端发送一条消息,指出找不到该文件。我在服务器中包含了异常,但是我不知道如何在客户端中包含if子句:如果文件存在,则接收文件;如果文件存在,则接收文件。否则,收到消息说它不存在。我想我已经在服务器端做到了这一点,但是我不确定如何编写此代码,以便仅在服务器中找不到文件的情况下才在客户端中打印“文件未找到”消息。
这是服务器端代码

import socket
import os
import sys
import pickle

def Main():
host = '127.0.0.1'
port = 8881

s = socket.socket()
s.bind((host,port))
print("Server", host, "waiting on port", port)
s.listen(1)
while True:
c, addr = s.accept()
print("Connected to: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("File requested: " + filename)
if os.path.isfile(filename):
lista = []
myfile = os.path.getsize(filename)
size = ('File size: ',myfile,' bytes')
texto = ''
for i in size:
texto = texto + '{:>4}'.format(i)
print(texto)
lista.append(texto)
file_size = pickle.dumps(lista)
c.send(file_size)
file2send = open(filename, "rb")
c.send(file2send.read())
c.close()
else:
print("File not found")
msg = ('File not found')
s.send(msg.encode('utf-8'))


if __name__ == '__main__':
Main()
和客户端:
import socket, os.path, datetime, sys, pickle

def Main():
host = '127.0.0.1'
port = 8881

s = socket.socket()
s.connect((host, port))

Filename = input("File name and extension: ")
s.send(Filename.encode('utf-8'))
s.shutdown(socket.SHUT_WR)
file_size = s.recv(1024)
lista = pickle.loads(file_size)
print(lista)
data = s.recv(1024).decode('utf-8')
print(data)
msg = s.recv(1024).decode('utf-8')
print(msg)
s.close()

if __name__ == '__main__':
Main()

最佳答案

在服务器中,您正在将“找不到文件”消息发送到服务器套接字s,而是应将其发送到客户端c,并且根据您的逻辑,应先发送消息长度,然后发送消息,然后再关闭连接。
请引用下面的服务器代码。
服务器:

import socket
import os
import sys
import pickle

def Main():
host = '127.0.0.1'
port = 8881

s = socket.socket()
s.bind((host,port))
print("Server", host, "waiting on port", port)
s.listen(1)
while True:
c, addr = s.accept()
print("Connected to: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("File requested: " + filename)
if os.path.isfile(filename):
lista = []
myfile = os.path.getsize(filename)
size = ('File size: ',myfile,' bytes')
texto = ''
for i in size:
texto = texto + '{:>4}'.format(i)
print(texto)
lista.append(texto)
file_size = pickle.dumps(lista)
c.send(file_size)
file2send = open(filename, "rb")
c.send(file2send.read())
c.close()
else:
print("File not found")
msg = ('File not found')
c.send(str(len(msg)).encode('utf-8'))
c.send(msg.encode('utf-8'))
c.close()


if __name__ == '__main__':
Main()

关于python-3.x - 如何使用Python告诉客户端服务器中不存在文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63949426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com