python文件传输代码
我在这里找到了代码:(选择的答案) 但是我会再把它贴在这里python文件传输代码,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 binar
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()
server.py
导入套接字
导入系统
s=socket.socket()
s、 绑定((“localhost”,9999))
s、 听(10)
尽管如此:
sc,address=s.accept()
打印地址
i=1
f=open('file_'+str(i)+“.txt”,“wb')#以二进制形式打开
i=i+1
虽然(正确):
l=sc.recv(1024)
而(一):
打印l#程序运行时,您可能正在尝试检查文件。文件正在被缓冲,因此在执行f.close()
行之前,或者在写入大量数据之前,您可能不会在其中看到任何输出。在f.write(l)
行之后添加对f.flush()
的调用,以实时查看输出。请注意,这会在一定程度上影响性能。服务器代码无论如何都不起作用,我已经对其进行了修改以使其起作用
该文件为空,因为它在为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()
导入套接字
导入系统
s=socket.socket()
s、 绑定((“localhost”,9999))
s、 听(10)
i=1
尽管如此:
打印“将接受”
sc,address=s.accept()
打印“已接受”
打印地址
f=open('file_'+str(i)+“.txt”,“wb')#以二进制形式打开
i+=1
l=sc.recv(1024)
而(一):
f、 写(l)#你的缩进正确吗?我看不出它是如何从你的中间跳出来的,而True
,即使它从客户端套接字读取了所有数据,它也卡在了那个循环中。@sotapme:是的。我觉得是这样。我从这里复制了代码(选择的答案),我正在计算正确的缩进。如果你发现了,请告诉我。感谢我的想法,中间虽然True
是不必要的,但当你运行代码时,它会永远打印空白行,当它复制文件时。