只有在Control-C之后,Python文件传输才会完成

时间:2014-02-12 09:26:11

标签: python multithreading sockets file-transfer

我正在尝试多线程python程序同时由多个客户端连接到服务器。程序运行成功,但我尝试发送的图像具有不完整的数据,直到我使用Control C终止程序。在Control-C之后,文件重新加载并且完整图像可见。 我在这里发布我的代码: Server.py

from socket import *
import thread

def handler(clientsocket, clientaddr):
    print "Accepted connection from: ", clientaddr

    while 1:
        data = clientsocket.recv(8192)
        if not data:
            break
        else:
            print "The following data was received - ",data
            print "Opening file - ",data
            fp = open(data,'r')
            strng = "hi"
            while strng:
                strng = fp.read(8192)
                clientsocket.send (strng)


    clientsocket.close()

if __name__ == "__main__":

    host = 'localhost'
    port = 55574
    buf = 8192

    addr = (host, port)

    serversocket = socket(AF_INET, SOCK_STREAM)

    serversocket.bind(addr)

    serversocket.listen(5)

    while 1:
        print "Server is listening for connections\n"

        clientsocket, clientaddr = serversocket.accept()
        thread.start_new_thread(handler, (clientsocket, clientaddr))
    serversocket.close()

Client.py:

from socket import *
import os
if __name__ == '__main__':

    host = 'localhost'
    port = 55574
    buf = 8192

    addr = (host, port)

    clientsocket = socket(AF_INET, SOCK_STREAM)

    clientsocket.connect(addr)

    while 1:
        fname = raw_input("Enter the file name that u want>> ")
        if not fname:
            break
        else:
            clientsocket.send(fname)
            print "\nThe file will be saved and opened- "
            fname = '/home/coep/Downloads/'+fname
            nf = open(fname,"a")
            strng = "hi"
            while strng:
                strng = clientsocket.recv(8192)
                nf.write(strng)

            nf.close()
            fname = 'viewnior '+ fname
            print fname
            os.system(fname)

2 个答案:

答案 0 :(得分:0)

尝试更改:

            while strng:
                strng = clientsocket.recv(8192)
                nf.write(strng)

要:

            while True:
                strng = clientsocket.recv(8192)
                if not strng:
                    break
                nf.write(strng)

答案 1 :(得分:0)

这段代码有很多问题:

1)服务器和客户端。发送和接收文件可能会很棘手。看看这个:

while strng:
    strng = clientsocket.recv(8192)
    nf.write(strng)

无限循环。你必须添加

while strng:
    strng = clientsocket.recv(8192)
    if not strng:
        break
    nf.write(strng)

到服务器。但客户端不知道您何时停止传输文件(这是您问题的根源)。因此,您必须发送一些STOP值(如果文件包含此类字符串可能会很棘手)或在发送内容之前发送文件大小(因此客户端将知道应该读取多少数据)。第二种解决方案是首选(例如HTTP的工作方式)。

2)不要使用thread模块。这是低水平,很容易犯错误。使用threading

3)服务器。您使用fp = open(data,'r')打开文件,但不要在任何地方关闭它。而是使用with

with open(data, 'r') as fp:
    # the code that uses fp goes here

一旦离开块,它将自动关闭文件。

4)除非绝对必要,否则不要使用os.system。我知道这只是用于调试,但无论如何都是一个很好的建议。

5)如果您不想打扰系统socket.sendall电话的棘手内部,请使用socket.send代替send。在你的情况下可能无关紧要。