1. 程式人生 > >python socket文件傳輸實現

python socket文件傳輸實現

通信 服務 操作系統 for 寫入 127.0.0.1 total serve mp4

簡單版

server(服務端)

import socket
import subprocess
import struct
import json
import os

share_dir = rE:\server\share  # 需要傳輸的文件所在的文件夾

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 回收重用端口10000
phone.bind((127.0.0.1, 10000))  #
0-65535 0-1024給操作系統, phone.listen(5) print(stearting) while True: # 建鏈接循環 conn, client_addr = phone.accept() print(client_addr) while True: # 通信循環 try: # 1.收命令 res = conn.recv(1024) # get jiaoyue.mp4 # 2.解析命令,提取相應命令參數 cmds = res.decode(
utf-8).split() # [‘get‘, ‘jiaoyue.mp4‘] filename = cmds[1] # 3.以讀的方式打開 # 1制作報頭 header_dic = { filename: filename, md5: xxdxx, file_size: os.path.getsize(r%s/%s % (share_dir, filename)) #
E:\study\第3模塊,面向對象\網絡編程\文件傳輸\server\share\jiaoyue.mp4 } header_json = json.dumps(header_dic) header_bytes = header_json.encode(utf-8) # 2 發送報頭長度 conn.send(struct.pack(i, len(header_bytes))) # 固定長度4 # 3 發報頭 conn.send(header_bytes) # 4發真實數據 with open(%s/%s % (share_dir, filename), rb) as f: # conn.send(f.read()) for a in f: conn.send(a) except ConnectionResetError: break conn.close() phone.close()

client(客戶端)

import socket
import struct
import json

download_dir = rE:\client\download  # 文件存放地址

pc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
pc.connect((127.0.0.1, 10000))

while True:
    # 1.發命令
    cmd = input(>>>:).strip()  # get a.text
    if not cmd:
        continue
    pc.send(cmd.encode(utf-8))

    # 2.接受文件內容,以寫的方式打開一個新文件,寫入客戶端新文件中

    # 1收報頭長度
    obj = pc.recv(4)
    header_size = struct.unpack(i, obj)[0]

    # 2接收報頭
    header_bytes = pc.recv(header_size)

    # 3解析報頭,對於數據的描述
    header_json = header_bytes.decode(utf-8)
    header_dic = json.loads(header_json)
    print(header_dic)
    total_size = header_dic[file_size]
    file_name = header_dic[filename]

    # 4 接受真實的數據
    with open(%s/%s % (download_dir, file_name), wb) as f:
        recv_size = 0
        while recv_size < total_size:
            res = pc.recv(1024)
            f.write(res)
            recv_size += len(res)
            print(總大小:%s  已經下載大小:%s % (total_size, recv_size))

pc.close()

優化之後的版本

server

import socket
import struct
import json
import os


share_dir = rE:\server\share‘  # 文件地址

def get(cmds, conn):
    filename = cmds[1]
    # 3.以讀的方式打開,讀取文件
    # 1制作報頭
    header_dic = {
        filename: filename,
        md5: xxdxx,
        file_size: os.path.getsize(r%s/%s % (share_dir, filename))  # E:\study\第3模塊,面向對象\網絡編程\文件傳輸\server\share\jiaoyue.mp4
    }
    header_json = json.dumps(header_dic)
    header_bytes = header_json.encode(utf-8)

    # 2 發送報頭長度
    conn.send(struct.pack(i, len(header_bytes)))  # 固定長度4

    # 3 發報頭
    conn.send(header_bytes)
    # 4發真實數據
    with open(%s/%s % (share_dir, filename), rb) as f:
        # conn.send(f.read())
        for a in f:
            conn.send(a)

def put(pc):
    # 2.接受文件內容,以寫的方式打開一個新文件,寫入客戶端新文件中
    # 1收報頭長度
    obj = pc.recv(4)
    header_size = struct.unpack(i, obj)[0]

    # 2接收報頭
    header_bytes = pc.recv(header_size)

    # 3解析報頭,對於數據的描述
    header_json = header_bytes.decode(utf-8)
    header_dic = json.loads(header_json)
    print(header_dic)
    total_size = header_dic[file_size]
    file_name = header_dic[filename]

    # 4 接受真實的數據
    with open(%s/%s % (share_dir, file_name), wb) as f:
        recv_size = 0
        while recv_size < total_size:
            res = pc.recv(1024)
            f.write(res)
            recv_size += len(res)
            print(總大小:%s  已經下載大小:%s % (total_size, recv_size))

def run():
    phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 回收重用端口10000
    phone.bind((127.0.0.1, 10000))  # 0-65535  0-1024給操作系統,
    phone.listen(5)
    while True:  # 建鏈接循環
        conn, client_addr = phone.accept()
        print(client_addr)
        while True:  # 通信循環
            try:
                # 1.收命令
                res = conn.recv(1024)  # get jiaoyue.mp4
                # 2.解析命令,提取相應命令參數
                cmds = res.decode(utf-8).split()  # [‘get‘, ‘jiaoyue.mp4‘]
                if cmds[0] == get:
                    get(cmds, conn)
                elif cmds[0] == put:
                    put(conn)
            except ConnectionResetError:
                break
        conn.close()
    phone.close()

if __name__ == __main__:
    run()

client

import socket
import struct
import json
import os

download_dir = rE:\client\download‘  # 文件存放地址

def get(pc):
    # 2.接受文件內容,以寫的方式打開一個新文件,寫入客戶端新文件中
    # 1收報頭長度
    obj = pc.recv(4)
    header_size = struct.unpack(i, obj)[0]

    # 2接收報頭
    header_bytes = pc.recv(header_size)

    # 3解析報頭,對於數據的描述
    header_json = header_bytes.decode(utf-8)
    header_dic = json.loads(header_json)
    print(header_dic)
    total_size = header_dic[file_size]
    file_name = header_dic[filename]

    # 4 接受真實的數據
    with open(%s/%s % (download_dir, file_name), wb) as f:
        recv_size = 0
        while recv_size < total_size:
            res = pc.recv(1024)
            f.write(res)
            recv_size += len(res)
            print(總大小:%s  已經下載大小:%s % (total_size, recv_size))

def put(cmds, conn):
    filename = cmds[1]
    # 3.以讀的方式打開,讀取文件
    # 1制作報頭
    header_dic = {
        filename: filename,
        md5: xxdxx,
        file_size: os.path.getsize(r%s/%s % (download_dir, filename))
    }
    header_json = json.dumps(header_dic)
    header_bytes = header_json.encode(utf-8)

    # 2 發送報頭長度
    conn.send(struct.pack(i, len(header_bytes)))  # 固定長度4

    # 3 發報頭
    conn.send(header_bytes)
    # 4發真實數據
    send_size = 0
    with open(%s/%s % (download_dir, filename), rb) as f:
        # conn.send(f.read())
        for a in f:
            conn.send(a)
            send_size += len(a)
            print(send_size)

def run():
    pc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    pc.connect((127.0.0.1, 10000))
    print(pc)
    while True:
        # 1.發命令
        inp = input(>>>:).strip()  # get a.text
        if not inp:
            continue
        pc.send(inp.encode(utf-8))
        cmds = inp.split()
        if cmds[0] == get:
            get(pc)
        elif cmds[0] == put:
            put(cmds, pc)
    pc.close()

if __name__ == __main__:
    run()

python socket文件傳輸實現