我在这里找到了代码:通过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()