import sys, os, thread, time
from socket import *
def now(): return time.strftime('%Y-%m-%d %X',time.localtime())
bufsz = 1024
defaultHost = 'localhost'
defaultPort = 51111
path = '/sl4a/scripts/'
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 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') # send remote name with dir
file = open(filename, 'wb') # create local file in cwd
while True:
data = sock.recv(bufsz) # 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 get', filename, 'at', now( )
def serverthread(clientsock):
global path
sockfile = clientsock.makefile('r') # wrap socket in dup file obj
filename = sockfile.readline( )[:-1] # get filename up to end-line
dropdir = path + os.path.split(filename)[1]
try:
file = open(dropdir, 'rb')
while True:
bytes = file.read(bufsz) # read/send 1K at a time
if not bytes: break # until file totally sent
sent = clientsock.send(bytes)
assert sent == len(bytes)
file.close()
print 'download file :', dropdir
except:
print 'Error download 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':
name = gethostname()
host = gethostbyname(name) # else fails remotely
print host,port
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)
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
getfile.rar (2个子文件)
getfile.py 3KB
getfile2.py 2KB
共 2 条
- 1
资源评论
belldeep
- 粉丝: 630
- 资源: 50
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功