Socket实现文件传输

2019-12-18  本文已影响0人  OliverChu

使用了socket库来实现网络文件的传输,封装了下,希望您会喜欢,有任何问题也可以联系我

客户端

# -*- coding: utf-8 -*-
import socket
import argparse
import os
import hashlib
import pickle

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-f","--file",help="the file you want to send")
    parser.add_argument("-i","--ip",help="target's ip address")
    args = parser.parse_args()
    filePath = args.file
    ip = args.ip
    print "File path : %s" % filePath
    return filePath,ip

def read_file(filePath,eachCount):
    f = open(filePath,'r')
    size = os.path.getsize(filePath) * 1024
    print "Sent file size:",size
    data = ""
    tmp = f.read(eachCount)
    data += tmp
    while len(tmp) >0 :
        tmp = f.read(eachCount)
        data += tmp
    f.close()
    # print data
    md5_data = hashlib.md5(data).hexdigest()
    info = {
        'size':size,
        'md5':md5_data,
        'name':os.path.basename(filePath)
    }
    return data,info

if __name__ == "__main__":
    filePath,ip = parse_args()
    d,info = read_file(filePath,1024)
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    if not ip :
        ip = "127.0.0.1"
    s.connect((ip,9999))
    print s.recv(1024)
    s.sendall("#info#"+pickle.dumps(info))
    print s.recv(1024)
    s.send("#file#"+d)
    print s.recv(1024)
    s.send('exit')
    print s.recv(1024)
    s.close()

服务端:

# -*- coding: utf-8 -*-

import socket 
import time
import argparse
import threading
import os
import hashlib
import pickle

def tcplink(sock,addr):
    print "Now accept new connection from %s:%s..." %addr
    sock.send("ok")
    while True:
        data = sock.recv(2048)
        if data == "exit" or not data:
            break
        if data.startswith("#info#"):
            str_info = data[6:]
            info = pickle.loads(str_info)
            print info
            sock.send("ok")
            size = info['size']
            d = sock.recv(4096)
            print "Rec:",d
            if d.startswith("#file#"):
                if len(d) >= 4096:
                    d = d[6:]
                    write_file(info['name'],d)
                    while size >0 :
                        if size >= 4096:
                            print size
                            d = sock.recv(4096)
                            write_file(info['name'],d)
                            size -= 4096
                        else:
                            print "end",size
                            d = sock.recv(size)
                            size = 0
                            write_file(info['name'],d)
                else:
                    write_file(info['name'],d[6:])
            sock.send("ok")
    sock.send("bye")
    sock.close()
    print "Now disconnect socket from %s:%s..." %addr

def write_file(name,data):
    f = open("recv/%s"%name,"a+")
    f.write(data)
    print "recv/%s"%name
    f.close()

if __name__ == "__main__":
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind(("127.0.0.1",9999))
    s.listen(5)
    print "Waiting for connection..."
    while True:
        sock,addr = s.accept()
        t=threading.Thread(target=tcplink(sock,addr))

Usage:

python rec.py

python send.py -f '{file path}' -i '{ip address}'
上一篇下一篇

猜你喜欢

热点阅读