码迷,mamicode.com
首页 > 其他好文 > 详细

基于socket套接字low版ftp

时间:2019-09-09 22:45:42      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:json   end   客户   list   exce   code   enc   客户端   soc   

server

import socket
import struct
import json
while True:
    soc = socket.socket()
    soc.bind(('192.168.31.233', 8001))
    soc.listen(3)
    print('等待客户端连接')
    conn,addr=soc.accept()
    user = conn.recv(65535)
    user = str(user, encoding='utf8')
    pwd = conn.recv(65535)
    pwd = str(pwd, encoding='utf8')
    if user ==  'admin' and pwd == '123':
        conn.send(b'true')
        print('有个客户端连接上了',addr,'登陆成功')
        while True:
            try:
                data=conn.recv(65535)
                data = str(data,encoding='utf8')
                if data:
                    with open('D:\python\课程相关文件.zip','rb') as f:  ##随便本地一个文件
                        data = f.read()
                    dic={'size':len(data)}
                    dic_bytes=(json.dumps(dic)).encode('utf-8')
                    head_count=struct.pack('i',len(dic_bytes))
                    conn.send(head_count)
                    conn.send(dic_bytes)
                    conn.send(data)
            except Exception:
                break
    else:
        conn.send(b'false')
        print('账号或密码错误')
    conn.close()

client

import socket
import struct
import json
while True:
    soc = socket.socket()
    soc.connect(('192.168.31.233', 8001))
    user = input('请输入账号')
    soc.send(user.encode('utf-8'))
    pwd = input('请输入密码')
    soc.send(pwd.encode('utf8'))
    t_or_f = soc.recv(65535)
    if str(t_or_f,encoding='utf8') == 'true':
        choice=input('是否下载:')
        if choice == 'y':
            soc.send(choice.encode('utf-8'))
            head_dic_len=soc.recv(4)
            head_l=struct.unpack('i',head_dic_len)[0]
            dic_byte=soc.recv(head_l)
            head=json.loads(dic_byte)
            l=head['size']
            count=0
            data_total=b''
            print('下载中')
            while count<l:
                if l<65535:
                    data=soc.recv(l)
                else:
                    if l-count>=65535:
                        data=soc.recv(65535)
                    else:
                        data=soc.recv(l-count)
                data_total+=data
                count+=len(data)
            with open(r'D:\python\test\qwe.zip','wb') as f:
                f.write(data_total)
                f.flush()
            print('已完成')
        else:
            print('取消下载')
    elif str(t_or_f,encoding='utf8') == 'false':
        print('账号密码错误')
        soc.close()

可以在

基于socket套接字low版ftp

标签:json   end   客户   list   exce   code   enc   客户端   soc   

原文地址:https://www.cnblogs.com/oxtime/p/11494512.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!