[英]file transfer code python
我在這里找到了代碼: 通過Python中的套接字發送文件 (選定的答案)
但我會再次將其張貼在這里。
server.py
import socket
import sys
s = socket.socket()
s.bind(("localhost",9999))
s.listen(10)
while True:
sc, address = s.accept()
print address
i=1
f = open('file_'+ str(i)+".txt",'wb') #open in binary
i=i+1
while (True):
l = sc.recv(1024)
while (l):
print l #<--- i can see the data here
f.write(l) #<--- here is the issue.. the file is blank
l = sc.recv(1024)
f.close()
sc.close()
s.close()
client.py
import socket
import sys
s = socket.socket()
s.connect(("localhost",9999))
f=open ("test.txt", "rb")
l = f.read(1024)
while (l):
print l
s.send(l)
l = f.read(1024)
s.close()
在服務器代碼上,print l行將打印文件內容..表示正在傳輸內容..但是文件為空?
我想念什么? 謝謝
您可能正在嘗試在程序運行時檢查文件。 該文件正在緩沖中,因此在執行f.close()
行或寫入大量數據之前,您可能看不到任何輸出。 在f.write(l)
行之后添加對f.flush()
的調用,以實時查看輸出。 請注意,這會稍微影響性能。
那么服務器代碼還是無法正常工作,我對其進行了修改以使其正常工作。
該文件為空是因為它停留在while True
並且從未繞過關閉文件。
另外, i=1
處於循環內,因此它始終寫入同一文件。
import socket
import sys
s = socket.socket()
s.bind(("localhost",9999))
s.listen(10)
i=1
while True:
print "WILL accept"
sc, address = s.accept()
print "DID accept"
print address
f = open('file_'+ str(i)+".txt",'wb') #open in binary
i += 1
l = sc.recv(1024)
while (l):
f.write(l) #<--- here is the issue.. the file is blank
l = sc.recv(1024)
f.close()
sc.close()
print "Server DONE"
s.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.