A-A+

一屏python代码实现文件传送

2016年08月03日 python 暂无评论 阅读 2,034 次
------------------------------------------------------------------- 服务端: 接收文件 #./file-server.py
#!/usr/bin/python
import SocketServer
 
# Format: name_len      --- one byte
#         name          --- name_len bytes
#         data          --- variable length
# Save data to name into current directory
addr = ('192.168.230.128', 1234)
class MyTCPHandler (SocketServer.StreamRequestHandler):
        def handle (self):
                name_len = ord(self.rfile.read(1))
                name = self.rfile.read(name_len)
                print "Get request:%s"%name
                fd = open(name, 'w')
                cont = self.rfile.read(4096)
                while cont:
                        fd.write(cont)
                        cont = self.rfile.read(4096)
                fd.close()
                print "Out :%s"%name
 
server = SocketServer.TCPServer(addr, MyTCPHandler)
server.serve_forever()
------------------------------------------------------------------- 客户端:发送文件 #./python/file-client.py zabbix-2.5.0.tar.gz
#!/usr/bin/python
from socket import *
import os.path
import sys
target = ('192.168.230.128',1234)
def get_header (name):
        leng = len(name)
        assert leng < 250
        return chr(leng) + name
 
def send_file (name):
        basename = os.path.basename(name)
        header = get_header(basename)
        cont = open(name).read()
        s = socket (AF_INET, SOCK_STREAM)
        s.connect(target)
        s.sendall (header)
        s.sendall (cont)
        s.close()
 
for i in sys.argv[1:]:
        print i
        send_file (i)
-------------------------------------------------------------------
标签:

给我留言