我有一個使用套接字進行通信的服務器和一個客戶端。服務器需要能夠使用命令“grab”(例如,grab text.txt)從客戶端下載檔案。但是當客戶端發回檔案名和資料下載時,服務器將檔案名解釋為名稱 資料。
服務器
try:
conn.send(cmd.encode(ENCODING))
resp = conn.recv(BUFFER).decode(ENCODING)
except (BrokenPipeError, IOError, TypeError):
print('The connection is no longer available')
resp_split = resp.split(' ')
if resp_split[0] == 'grab':
filename1 = resp_split[1:]
filename = ' '.join([str(elem) for elem in filename1]) #Converts list to str
filedata1 = resp_split[2:]
filedata = ' '.join([str(elem) for elem in filedata1]) #Converts list to str
f = open(filename,"w ")
f.write(filedata)
time.sleep(2)
f.close()
print(filename.removesuffix(filedata))
else:
resp = resp[2:-1]
print(resp)
客戶
command = sock.recv(COMMMAND_SIZE).decode('utf-8') # Receive command from server.
command_output = 'Invalid command.'
cmd_split = command.split(' ')
if cmd_split[0] == 'grab':
args1 = cmd_split[1:]
args = ' '.join([str(elem) for elem in args1])
try:
with open(args,'r') as file:
file_data = "grab " args ' ' file.read()
command_output = file_data
except Exception as e:
print(e)
else:
command_output = self.exec_windows_cmd(command)
sock.send(bytes(str(command_output), 'utf-8'))
發生的情況是服務器發送“grab text.txt”,客戶端以“grab text.txt example text 1234”回應,服務器收到此訊息,需要取出檔案名的 text.txt 和“example text 1234”檔案資料。而是將檔案命名為“text.txt 示例文本 1234”,并正確地將“示例文本 1234”放入檔案中。
uj5u.com熱心網友回復:
如果你寫resp_split[1:]python 從串列中抓取所有專案,包括索引 1 之后。
但是您只想要索引 1 處的專案,所以它應該是:
filename = resp_split[1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/421973.html
標籤:
上一篇:Python異步http服務器
