我正在编写一个TCP并发(基于进程的并发)服务器,它接受一个下载命令 . 客户端应该从服务器下载文件,截至目前我已经下载了硬编码的文件名以便测试我的下载算法 .
我查找了一个示例download algorithm并使用了该代码中使用的while循环 .
我认为我的问题是,其中一个while循环(或者它们两个)都被挂起并且不会结束 . 我相信它是客户端,它可能正在等待更多的fileContent .
服务器
file = open('download.txt','rb+')
print "Opened File: " , file.name
fileContent = file.read(1)
clientsocket.send(fileContent)
while (fileContent):
print "iteration", fileContent
clientsocket.send(fileContent)
fileContent = file.read(1)
file.close()
客户端
print "Attempting download..."
f = open('downloaded.txt' , 'wb+')
print "Opened File: " , f.name
fileContent = s.recv(1)
while (fileContent):
print "iteration", fileContent
f.write(fileContent)
fileContent = s.recv(1)
print "Download Complete"
f.close()
我没有使用while循环完成文件传输,使用的代码如
f.open(file)
fContent = f.read(1024)
client.send(fContent)
f.close
f.open(file)
fContent = server.recv(1024)
f.write(fContent)
f.close
但我知道如果文件大于缓冲区大小会导致问题 .
这是一个并发服务器,它使用单个进程来处理每个连接 . (我不相信这会影响我当前的问题,但我是并发的新手,并认为我会提到它 . )
有谁知道为什么我的while循环没有结束?或者有人知道我可能做错的其他事吗?提前致谢!
编辑:
我的输出:
CLI
Attempting download...
Opened File: downloaded.txt
iteration t
iteration h
iteration i
iteration s
iteration
iteration i
iteration s
iteration
iteration a
iteration
iteration f
iteration i
iteration l
iteration e
iteration
SERV
Recived dl from: ('127.0.0.1', 38161) | 2015-12-06 13:07:12.835998
Opened File: download.txt
iteration t
iteration h
iteration i
iteration s
iteration
iteration i
iteration s
iteration
iteration a
iteration
iteration f
iteration i
iteration l
iteration e
iteration
客户端卡住了,我必须把它拉出来 . 服务器将继续接受连接 . 我刚刚意识到我可以在服务器的while循环之后添加一个简单的print语句来检查服务器的while循环是否完成 .
第二次编辑:
服务器没有挂起(它在循环后成功显示消息) . 这让我相信客户端正在调用recv()并等待更多的fileContent .
第3编辑:
读/写缓冲区仅为1用于测试目的 .
1 回答
逐字节发送文件可能会非常慢 . 最好使用
shutil.copyfileobj
,为您处理转移: