簡體   English   中英

使用python的tcp套接字發送和接收文件

[英]Tcp sockets to send and receive files, using python

我試圖使簡單的客戶端服務器程序使用tcp套接字發送和接收文件形式的服務器。 至於從服務器獲取文件不是問題,服務器會創建一個具有相同名稱的文件並將數據放入該文件中,但是當涉及到將文件放入服務器時,雖然有時效果很好,但總是有機會,因此多數情況下服務器正在獲取文件名連同文件內容一起,而不是將其寫入文件,它會將文件名和內容都寫為新文件名,並且該文件保持為空。 如果有人可以提出任何解決方案,那將是很大的幫助。

server.py

import socket
import sys
HOST = 'localhost'
PORT = 3820

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))

socket.listen(1)
while (1):
    conn, addr = socket.accept()
    print 'New client connected ..'
    reqCommand = conn.recv(1024)
    print 'Client> %s' %(reqCommand)
    if (reqCommand == 'quit'):
        break
    #elif (reqCommand == lls):
        #list file in server directory
    else:
        string = reqCommand.split(' ', 1)   #in case of 'put' and 'get' method
        reqFile = string[1]

        if (string[0] == 'put'):
            with open(reqFile, 'wb') as file_to_write:
                data=conn.recv(1024)
                while True:
                    if not data:
                        break
                    else:
                        file_to_write.write(data)
                        data=conn.recv(1024)
                    file_to_write.close()
                    break
            print 'Receive Successful'
        elif (string[0] == 'get'):
            with open(reqFile, 'rb') as file_to_send:
                for data in file_to_send:
                    conn.sendall(data)
            print 'Send Successful'
    conn.close()

socket.close()

client.py

    import socket
import sys

HOST = 'localhost'    # server name goes in here
PORT = 3820


def put(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)
    string = commandName.split(' ', 1)
    inputFile = string[1]
    with open('clientfolder/'+inputFile, 'rb') as file_to_send:
        data=file_to_send.read(1024)
        while(data):
            socket1.send(data)
            data=file_to_send.read(1024)
            file_to_send.close()
    print 'PUT Successful'
    socket1.close()
    return


def get(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)
    string = commandName.split(' ', 1)
    inputFile = string[1]
    with open('clientfolder/'+inputFile, 'wb') as file_to_write:
        while True:
            data = socket1.recv(1024)
            # print data
            if not data:
                break
            # print data
            file_to_write.write(data)
    file_to_write.close()
    print 'GET Successful'
    socket1.close()
    return


msg = raw_input('Enter your name: ')
while(1):
    print 'Instruction'
    print '"put [filename]" to send the file the server '
    print '"get [filename]" to download the file from the server '
    print '"ls" to list all files in this directory'
    print '"lls" to list all files in the server'
    print '"quit" to exit'
    sys.stdout.write('%s> ' % msg)
    inputCommand = sys.stdin.readline().strip()
    if (inputCommand == 'quit'):
        socket.send('quit')
        break
    # elif (inputCommand == 'ls')
    # elif (inputCommand == 'lls')
    else:
        string = inputCommand.split(' ', 1)
        if (string[0] == 'put'):
            put(inputCommand)
        elif (string[0] == 'get'):
            get(inputCommand)
#current working directory is server location
#get will get file from current directory to clientfolder directory.

TCP是一種流協議,因此您必須在協議中設計消息中斷。 例如:

s.send('put filename')
s.send('data')

可以通過以下方式接收:

s.recv(1024)
# 'put filenamedata'

因此,緩沖接收到的數據,僅提取完整的消息。 一種方法是在消息之前發送消息的大小。

暫無
暫無

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

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