前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 文件下载服务器 脚本

python 文件下载服务器 脚本

作者头像
用户5760343
发布2022-05-13 10:08:22
2.2K0
发布2022-05-13 10:08:22
举报
文章被收录于专栏:sktj

import sys, os, time, _thread as thread from socket import *

blksz = 1024 defaultHost = 'localhost' defaultPort = 50001

helptext = """ Usage... server=> getfile.py -mode server [-port nnn] [-host hhh|localhost] client=> getfile.py [-mode client] -file fff [-port nnn] [-host hhh|localhost] """

def now(): return time.asctime()

def parsecommandline(): dict = {} # put in dictionary for easy lookup args = sys.argv[1:] # skip program name at front of args while len(args) >= 2: # example: dict['-mode'] = 'server' dict[args[0]] = args[1] args = args[2:] return dict

def client(host, port, filename): sock = socket(AF_INET, SOCK_STREAM) sock.connect((host, port)) sock.send((filename + '\n').encode()) # send remote name with dir: bytes dropdir = os.path.split(filename)[1] # filename at end of dir path file = open(dropdir, 'wb') # create local file in cwd while True: data = sock.recv(blksz) # get up to 1K at a time if not data: break # till closed on server side file.write(data) # store data in local file sock.close() file.close() print('Client got', filename, 'at', now())

def serverthread(clientsock): sockfile = clientsock.makefile('r') # wrap socket in dup file obj filename = sockfile.readline()[:-1] # get filename up to end-line try: file = open(filename, 'rb') while True: bytes = file.read(blksz) # read/send 1K at a time if not bytes: break # until file totally sent sent = clientsock.send(bytes) assert sent == len(bytes) except: print('Error downloading file on server:', filename) clientsock.close()

def server(host, port): serversock = socket(AF_INET, SOCK_STREAM) # listen on TCP/IP socket serversock.bind((host, port)) # serve clients in threads serversock.listen(5) while True: clientsock, clientaddr = serversock.accept() print('Server connected by', clientaddr, 'at', now()) thread.start_new_thread(serverthread, (clientsock,))

def main(args): host = args.get('-host', defaultHost) # use args or defaults port = int(args.get('-port', defaultPort)) # is a string in argv if args.get('-mode') == 'server': # None if no -mode: client if host == 'localhost': host = '' # else fails remotely server(host, port) elif args.get('-file'): # client mode needs -file client(host, port, args['-file']) else: print(helptext)

if name == 'main': args = parsecommandline() main(args)


文件下载客户端:gui

import sys, os from tkinter import * from tkinter.messagebox import showinfo

def onReturnKey(): cmdline = ('python getfile.py -mode client -file %s -port %s -host %s' % (content['File'].get(), content['Port'].get(), content['Server'].get())) os.system(cmdline) showinfo('getfilegui-1', 'Download complete')

box = Tk() labels = ['Server', 'Port', 'File'] content = {} for label in labels: row = Frame(box) row.pack(fill=X) Label(row, text=label, width=6).pack(side=LEFT) entry = Entry(row) entry.pack(side=RIGHT, expand=YES, fill=X) content[label] = entry

box.title('getfilegui-1') box.bind('<Return>', (lambda event: onReturnKey())) mainloop()

----------------------------------------------------------------------或者 import getfile from tkinter import * from tkinter.messagebox import showinfo

def onSubmit(): getfile.client(content['Server'].get(), int(content['Port'].get()), content['File'].get()) showinfo('getfilegui-2', 'Download complete')

box = Tk() labels = ['Server', 'Port', 'File'] rownum = 0 content = {} for label in labels: Label(box, text=label).grid(column=0, row=rownum) entry = Entry(box) entry.grid(column=1, row=rownum, sticky=E+W) content[label] = entry rownum += 1

box.columnconfigure(0, weight=0) # make expandable box.columnconfigure(1, weight=1) Button(text='Submit', command=onSubmit).grid(row=rownum, column=0, columnspan=2)

box.title('getfilegui-2') box.bind('<Return>', (lambda event: onSubmit())) mainloop()

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文件下载客户端:gui
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档