在Python上使用套接字进行文件传输

时间:2013-01-27 00:42:34

标签: python sockets

尝试使用Python上的套接字构建简单的文件传输。我卡住了,似乎我无法发送文件的任何部分。

根据一些建议,我试图发送文件的最后一行,这样我就可以知道何时完成连接。

但实际上,一旦我发送了第一个包,客户就永远不会得到其余的包。

在这里,您将看到我的代码(服务器端):

import os
import socket
PORT = 8080
HOST = 'localhost'
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST,PORT))
socket.listen(10)
conn, addr = socket.accept()
print '\033[46m\033[34m\033[1mBienvenido al File Sender v.0.02 hecho en Python. Este         programa permite enviar archivos a traves de tu maquina\033[0m'
ANSI_RED = '\033[31m'
ANSI_BLUE = '\033[34m'
ESCAPEANSI = '\033[0m'
def seleccion_path():
PATH = raw_input('\033[34m\033[1mSelect the Path (./ by default)').strip('n')
if PATH == '':
    PATH = os.getcwd()   
print PATH, ESCAPEANSI
acepta_path = raw_input('\033[34m\033[1mSi o No (S/N)').lower().strip(' ')
if acepta_path == 's' or acepta_path == 'si':
    return PATH
else:
    seleccion_path()
def filesDir(path):
files = os.listdir(PATH)
for fl in files:
    i = int(files.index(fl))+1
    print ANSI_RED + str(i)+ ')' + fl
return files

PATH = seleccion_path()
print 'el PATH seleccionado es:', PATH + '\n'
filesDir(PATH)
fileSelected = int(raw_input(ANSI_BLUE + 'Select a file with the number').strip(' ').lower()) 
print PATH + filesDir(PATH)[fileSelected-1]
fileToSend = open(PATH + filesDir(PATH)[fileSelected-1], 'rb')
qLines = len(open(PATH + filesDir(PATH)[fileSelected-1], 'rb').readlines())

finalLine = cpfileToSend.readlines()[qLines-1]
conn.send(finalLine)
while True:
    data = conn.sendall(fileToSend.readline())
    conf = conn.recv(1024)
    print conf
    if conf == 'OK':
        conn.close()
        fileToSend.close()
         break
print '\033[43m File sent'
#Finaliza el programa y deja los codigos ANSI cerrados
print ESCAPEANSI
exit()

以下是客户:

import os
import socket
PORT = 8080
HOST = 'localhost'

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST, PORT))
fname = open('./fileSent.pdf', 'w+')

finalLine = socket.recv(1024)
print finalLine
while True:
    strng = socket.recv(2048)
    print 'aaaaa',strng
    fname.write(strng)
    if finalLine in strng:
        fname.write(strng)
        socket.send('OK')
        socket.close()
fname.close()
print 'Data received correctly' 
exit()

2 个答案:

答案 0 :(得分:2)

最后我能够做到。问题出在socket.recv()上。我要求应用程序执行多行,但没有从服务器到达。客户端从未执行过该行以下的行,因为它期望数据继续运行下一行。 我重新安排了代码来处理这个问题,而且它运行得很好。 绝对喜欢Python:)

服务器端:

import os
import socket
PORT = 8080
HOST = 'localhost'
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST,PORT))
socket.listen(1)
conn, addr = socket.accept()
print '\033[46m\033[34m\033[1mBienvenido al File Sender v.0.02 hecho en Python. Este programa permite enviar archivos a traves de tu maquina\033[0m'
ANSI_RED = '\033[31m'
ANSI_BLUE = '\033[34m'
ESCAPEANSI = '\033[0m'
def seleccion_path():
PATH = raw_input('\033[34m\033[1mSelect the Path (./ by default)').strip('n')
if PATH == '':
    PATH = os.getcwd()   
print PATH, ESCAPEANSI
acepta_path = raw_input('\033[34m\033[1mSi o No (S/N)').lower().strip(' ')
if acepta_path == 's' or acepta_path == 'si':
    return PATH
else:
    seleccion_path()
def filesDir(path):
files = os.listdir(PATH)
for fl in files:
    i = int(files.index(fl))+1
    print ANSI_RED + str(i)+ ')' + fl
return files

PATH = seleccion_path()
print 'el PATH seleccionado es:', PATH + '\n'
filesDir(PATH)
fileSelected = int(raw_input(ANSI_BLUE + 'Select a file with the number').strip(' ').lower()) 
print PATH + filesDir(PATH)[fileSelected-1]

filepath = PATH + filesDir(PATH)[fileSelected-1]
#envia nombre del file
conn.send(filepath)
qLines = len(open(PATH + filesDir(PATH)[fileSelected-1], 'rb').readlines())
fileToSend = open(filepath, 'rb')
while True:
data = fileToSend.readline()
if data:
    conn.send(data)
else:
    break
fileToSend.close()
conn.sendall('')
conn.close()

print '\033[43m File sent'  
#Finaliza el programa y deja los codigos ANSI cerrados
print ESCAPEANSI
exit()

客户方:

import os
import socket
PORT = 8080
HOST = 'localhost'

nombrearchivo = raw_input('define a name with its extension').strip(' ')
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST, PORT))
filename = socket.recv(1024)

fname = open('./'+nombrearchivo, 'wb')

while True:
strng = socket.recv(1024)
if strng:
    print strng
    fname.write(strng)
else:
    fname.close()
    break
socket.close()
print 'Data received correctly' 
exit()

答案 1 :(得分:1)

你的问题源于你打开文件,读取所有行(readlines),然后尝试再次读取文件而不关闭它。

我与@ T_12分享了为什么要先发送文件的最后一行的问题。但假设您需要这样做,以下是您需要的修复:

替换你的severside代码的这一部分(因为我没有看到你定义的地方cpfileToSend,我认为它应该是fileToSend

fileToSend = open(PATH + filesDir(PATH)[fileSelected-1], 'rb')
qLines = len(open(PATH + filesDir(PATH)[fileSelected-1], 'rb').readlines())

finalLine = cpfileToSend.readlines()[qLines-1]
conn.send(finalLine)
while True:
    data = conn.sendall(fileToSend.readline())
    conf = conn.recv(1024)
    print conf
    if conf == 'OK':
        conn.close()
        fileToSend.close()
         break

用这个

filepath = PATH + filesDir(PATH)[fileSelected-1]
fileToSend = open(filepath, 'rb')
qLines = len(open(PATH + filesDir(PATH)[fileSelected-1], 'rb').readlines())

finalLine = fileToSend.readlines()[qLines-1]
conn.send(finalLine)
fileToSend.close()
fileToSend = open(filepath, 'rb')
while True:
    data = conn.sendall(fileToSend.readline())
    conf = conn.recv(1024)
    print conf
    if conf == 'OK':
        conn.close()
        fileToSend.close()
         break

希望这有帮助