Python文件传输代码

2 投票
2 回答
1470 浏览
提问于 2025-04-17 15:26

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

在服务器的代码中,打印的那一行会显示文件的内容..这说明内容正在被传输..

但是文件却是空的??

我漏掉了什么吗?谢谢

2 个回答

2

那个服务器的代码反正没用,我把它改了一下,让它能正常工作。

文件之所以是空的,是因为它一直卡在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()
4

你可能是在程序运行的时候查看文件。这个文件是被缓冲的,所以在执行到f.close()这一行之前,或者在写入大量数据之前,你可能看不到里面的任何内容。你可以在f.write(l)这一行后面加上f.flush(),这样就能实时看到输出了。不过要注意,这样会稍微影响程序的性能。

撰写回答