python for android: pad 從PC接收檔案

來源:互聯網
上載者:User

如果不用USB線, pad 怎樣從PC接收檔案 ? 我在家用無線路由器, pad 用WiFi 連網.

Windows PC 上先啟動服務程式 getfile.py -mode server

import sys, os, thread, timefrom socket import *def now(): return time.strftime('%Y-%m-%d %X',time.localtime())bufsz = 1024defaultHost = 'localhost'defaultPort = 55555path = '/python4android/'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 dictdef 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)        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        server(host, port)    elif args.get('-file'):                       # client mode needs -file        client(host, port, args['-file'])    else:        print helptextif __name__ == '__main__':    args = parsecommandline( )    main(args)

cmd 用 ipconfig 看PC的IP地址.

android pad 運行 getfile.py

# -*- coding: utf8 -*-import androidimport sys, os, timefrom socket import *def now(): return time.strftime('%Y-%m-%d %X',time.localtime())droid = android.Android()filename = droid.dialogGetInput(u"從PC接收檔案",u"請輸入檔案名稱:").resultprint filenamebufsz = 1024host = '192.168.0.103'port = 55555path = '/mnt/sdcard/sl4a/scripts/'sock = socket(AF_INET, SOCK_STREAM)sock.connect((host, port))sock.send(filename + '\n')                 # send remote name with dirfile = open(path+filename, 'wb')                 # create local file in cwdwhile 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 filesock.close( )file.close( )print 'Client get', filename, 'at', now( )
在android 4.1 pad 上測試通過.



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.