簡體   English   中英

在Python上使用套接字進行文件傳輸

[英]File Transfer with Sockets on Python

嘗試使用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()

最后我能夠做到。 問題出在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()

您的問題源於這樣一個事實:您打開文件,讀取所有行(帶有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

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM