16 Star 44 Fork 45

现任明教教主-乾颐堂 / qytang_Python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
2016.1.19 Python文件服务器 1.90 KB
一键复制 编辑 原始数据 按行查看 历史
现任明教教主-乾颐堂 提交于 2016-01-19 10:59 . new file
import sys, os, time, _thread as thread
from socket import *
blksz = 100
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 = {}
args = sys.argv[1:]
while len(args) >= 2:
dict[args[0]] = args[1]
args = args[2:]
return dict
def client(host, port, filename):
print(filename)
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
sock.send((filename + '\n').encode())
dropdir = os.path.split(filename)[1]
print(dropdir)
file = open(dropdir, 'wb')
while True:
data = sock.recv(blksz)
if not data: break
file.write(data)
sock.close()
file.close()
print('Client got', filename, 'at', now())
def serverthread(clientsock):
sockfile = clientsock.makefile('r')
filename = sockfile.readline()[:-1]
print(filename)
file = open(filename, 'rb')
try:
while True:
bytes = file.read(blksz)
if not bytes: break
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)
serversock.bind((host, port))
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)
port = int(args.get('-port', defaultPort))
if args.get('-mode') == 'server':
if host == 'localhost': host = ''
server(host, port)
elif args.get('-file'):
client(host, port, args['-file'])
else: print(helptext)
if __name__ == '__main__':
args = parsecommandline()
main(args)
Python
1
https://gitee.com/qytang/qytang_Python.git
git@gitee.com:qytang/qytang_Python.git
qytang
qytang_Python
qytang_Python
master

搜索帮助