我有这个简单的python服务器 - 客户端的文件传输项目正在进行。 有两个部分,以每一面。 首先,客户端发送一个文件到服务器的第一部分。 然后服务器会将一行并将文件发送回客户端的第二部分。
我的问题是,由于某种原因,服务器代码粘贴在接受每当我在它返回的文件代码。 如果我注释掉的代码的第二部分,服务器接收到所有客户端发送的文件。 否则,它冻结在接收。 是的,客户没有发送。
你可以忽略所有的打印命令,就在那里看到问题的所在。
servercode:
import socket
ssFT = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssFT.bind((socket.gethostname(), 8756))
ssFT.listen(1)
while True:
(conn, address) = ssFT.accept()
text_file = 'fileProj.txt'
#Receive, output and save file
with open(text_file, "wb") as fw:
print("Receiving..")
while True:
print('receiving')
data = conn.recv(1024)
print('Received: ', data.decode('utf-8'))
if not data:
print('Breaking from file write')
break
fw.write(data)
print('Wrote to file', data.decode('utf-8'))
fw.close()
print("Received..")
#Append and send file
print('Opening file ', text_file)
with open(text_file, 'ab+') as fa:
print('Opened file')
print("Appending string to file.")
string = b"Append this to file."
fa.write(string)
fa.seek(0, 0)
print("Sending file.")
while True:
data = fa.read(1024)
conn.send(data)
if not data:
break
fa.close()
print("Sent file.")
break
ssFT.close()
客户代码:
import socket
csFT = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
csFT.connect((socket.gethostname(), 8756))
text_file = 'passphrase.txt'
#Send file
with open(text_file, 'rb') as fs:
#Using with, no file close is necessary,
#with automatically handles file close
while True:
data = fs.read(1024)
print('Sending data', data.decode('utf-8'))
csFT.send(data)
print('Sent data', data.decode('utf-8'))
if not data:
print('Breaking from sending data')
break
fs.close()
#Receive file
print("Receiving..")
with open(text_file, 'wb') as fw:
while True:
data = csFT.recv(1024)
if not data:
break
fw.write(data)
fw.close()
print("Received..")
csFT.close()