socket 实现udp 上传下载

from socket import *
import struct,sys
get_filename = None
def sock_config():
    global  get_filename
    get_filename = input("请输入下载的文件名:")
    send_data = struct.pack("!H"+str(len(get_filename))+"sb5sb",1,get_filename.encode("utf-8"),0,"octet".encode("utf-8"),0)
    udp_socket = socket(AF_INET, SOCK_DGRAM)
    udp_socket.bind(('',65533))
    udp_socket.sendto(send_data,("172.16.0.134",69))
    udp_socket.close()
    #sock_send = socket()
def sock_requst():
    request_sock = socket(AF_INET,SOCK_DGRAM)
    request_sock.bind(('',65533))
    create_file = False
    open_value = None
    check = 1
    while True:
        ret, recv_addr = request_sock.recvfrom(1024)
        oper = struct.unpack("!HH",ret[:4])

        if oper[0] == 5:
            print("文件不存在!")
            break
        else:
            create_file = True
        if create_file and open_value == None:
            f = open(get_filename, "wb+")
            open_value = 1
            create_file = False
        print(check," ",oper[1])
        if check == oper[1]:
            f.write(ret[4:])
        request_sock.sendto(struct.pack("!HH",4,oper[1]),(recv_addr[0],recv_addr[1]))
        print(oper, recv_addr, ret)
        #print("---第%d次写入---"%oper[1])
        if len(ret[4:]) < 512 :
            f.close()
            print("upload succend!")
            break
        check = oper[1]+1

    request_sock.close()
def mian():
    sock_config()
    sock_requst()
if __name__ == "__main__":
    mian()
from socket import *
import struct

def upload_request():
    send_Data = struct.pack("!H10sb5sb",2,"images.png".encode("utf-8"),0,"octet".encode("utf-8"),0)
    upload_socket = socket(AF_INET,SOCK_DGRAM)
    upload_socket.bind(('',65532))
    upload_socket.sendto(send_Data,("172.16.0.134",69))
    f = open("test.png","rb+")
    request_Data, recv_Addr = upload_socket.recvfrom(1024)[:4]
    request_ack, request_num = struct.unpack("!HH", request_Data[:4])
    num = 1
    if request_ack == 4 :
        while True:
            request_Data, recv_Addr = upload_socket.recvfrom(1024)[:4]
            request_ack, request_num = struct.unpack("!HH", request_Data[:4])
            if request_ack == 3 or request_ack == 4 :
                f_read = f.read(512)
                send_Data = struct.pack("!HH" + str(len(f_read)) + "s", 3,num,f_read)
                upload_socket.sendto(send_Data,recv_Addr)
            print(recv_Addr)
            print(request_ack,request_num,recv_Addr,send_Data)
            num += 1
    f.close()
    upload_socket.close()
if __name__ == "__main__":
    upload_request()

 

posted @ 2017-09-01 14:22  来世炸了幻想乡  阅读(478)  评论(0编辑  收藏  举报