Python客户端服务器传输.txt不写入文件

时间:2014-08-12 20:02:58

标签: python sockets tcp client file-transfer

我正在尝试使用TCP套接字在Python中编写一个简单的客户端/服务器,但我似乎无法弄清楚为什么文件没有传输。

客户端:

    import socket

    HOST = ''    #server name goes in here
    PORT = 3820             
    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.connect((HOST,PORT))

    fileToSend = open('myUpload.txt', 'rb')
    while True:
        data = fileToSend.readline()
        if data:
            socket.send(data)
        else:
            break
    fileToSend.close()
    print 'end'
    socket.close()
    exit()

打印结束只是告诉我该客户端已完成。

服务器:

    import socket
    HOST = ''                 
    PORT = 3820
    socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.bind((HOST, PORT))
    socket.listen(1)

    file = open('myTransfer.txt', 'wb')
    while True:
        conn, addr = socket.accept()
        data = conn.recv(1024)
        print data
        if data:
            file.write(data)
        else:
            file.close()
            break
    socket.close()

    exit()

服务器能够打印出客户端发送的正确数据,但无法将其保存到myTransfer.txt中。即使我在那里有一个break语句,程序似乎也无法终止。任何帮助都会非常有帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

您正在while循环中调用accept。因此,您只有一个recv调用接收数据,因此永远不会调用break

顺便说一下。你应该使用sendall来保证发送所有数据。

客户端:

import socket

HOST = ''    #server name goes in here
PORT = 3820             
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST,PORT))
with open('myUpload.txt', 'rb') as file_to_send:
    for data in file_to_send:
        socket.sendall(data)
print 'end'
socket.close()

服务器:

import socket
HOST = ''                 
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
conn, addr = socket.accept()
with open('myTransfer.txt', 'wb') as file_to_write:
    while True:
        data = conn.recv(1024)
        print data
        if not data:
            break
        file_to_write.write(data)
socket.close()