【发布时间】:2016-05-16 06:46:05
【问题描述】:
我正在尝试通过套接字传输文件,如果我在那之后立即关闭连接,它就可以正常工作 现在我想在上传完成后继续向服务器发送命令,但服务器只是忽略它们并认为文件还有更多行
到目前为止,这是我的代码 客户:
def client_sender():
global upload
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print target
print port
client.connect((target, port))
if upload:
with open(upload_destination, "rb") as f:
for line in f:
client.send(line)
f.close()
client.send("DONE\r\n")
upload = False
print client.recv(1024)
buffer = ""
buffer = sys.stdin.read()
#... some code for sending commands and receiving a response
服务器:
def handle_client(client_socket):
global upload
print "Client connected"
if upload:
file_buffer = ""
while True:
data = client_socket.recv(1024)
if data.rstrip() == "DONE":
break
file_buffer += data
try:
file_descriptor = open(upload_destination, 'wb')
file_descriptor.write(file_buffer)
file_descriptor.close()
client_socket.send("Successfully placed the file in %s" %upload_destination)
except:
client_socket.send("Failed writing to the file")
upload = False
#... same as client, just some more code for commands
【问题讨论】:
-
如果文件包含
DONE会发生什么会很有趣。 -
这是为了转移我编写的已编译的 C 程序,所以这不可能适得其反