Python 使用XML-RPC进行文件共享
1.目录结构
|__ config.ini
|__P2PClinet.py
|__P2PServer.py
|__url.txt
2.文件内容
config.ini
1
[SERVER_INFO]
2
PORT = 服务器端口号
3
DIRECTORY = 共享文件夹的路径
4
URL_FILE = url.txt
P2PClinet.py
001
'''
002
Created on 2012-7-21
003
004
author: Jeff_Yu
005
'''
006
007
from xmlrpclib import ServerProxy, Fault
008
from cmd import Cmd, PROMPT
009
from random import choice
010
from string import lower, lowercase
011
from P2PServer import Node, UNHANDLED
012
from threading import Thread
013
from time import sleep
014
import sys, ConfigParser, socket
015
016
HEAD_START = 0.1 # seconds
017
SECRET_LENGTH = 100
018
019
020
def randomString(length):
021
"""return the random string by given length"""
022
023
chars = []
024
letters = lowercase[:26]
025
while length > 0:
026
length -= 1
027
chars.append(choice(letters))
028
029
return ''.join(chars)
030
031
class Client(Cmd):
032
033
prompt = '>'
034
035
def __init__(self, url, dirname, urlfile):
036
037
Cmd.__init__(self)
038
self.secret = randomString(SECRET_LENGTH)
039
n = Node(url, dirname, self.secret)
040
t = Thread(target=n._start)
041
t.setDaemon(1)
042
t.start()
043
sleep(HEAD_START)
044
self.server = ServerProxy(url)
045
for line in open(urlfile):
046
line = line.strip()
047
self.server.hello(line)
048
049
050
def do_fetch(self, arg):
051
052
try:
053
self.server.fetch(arg, self.secret)
054
except Fault, f:
055
if f.faultCode != UNHANDLED: raise
056
print "Couldn't find the file", arg
057
058
def do_exit(self,arg):
059
060
print
061
sys.exit()
062
063
do_EOF = do_exit
064
065
class MyConfigParser:
066
067
def __init__(self, urlfile):
068
069
self.urlfile = urlfile
070
071
try:
072
f = open(self.urlfile,"r")
073
except IOError:
074
meg = "file %s is not found in the path >> %s" % (self.urlfile,os.path.abspath('.'))
075
return (0,meg)
076
077
self.config = ConfigParser.ConfigParser()
078
self.config.readfp(f)
079
080
f.close()
081
082
083
def getValueFromcfig(self,section,filed):
084
085
try:
086
value = self.config.get(section,filed)
087
except ConfigParser.NoOptionError:
088
meg = "%s is not found in file %s, under section %." %(filed, self.urlfile, section)
089
return (0,meg)
090
091
return(1,value)
092
093
094
095
def main():
096
097
configfile = "config.ini"
098
cfig = MyConfigParser(configfile)
099
100
#get port
101
res = cfig.getValueFromcfig("SERVER_INFO", 'PORT')
102
if (res[0] == 0):
103
print res[1]
104
raw_input()
105
sys.exit()
106
else:
107
port = res[1]
108
109
#get directory
110
res = cfig.getValueFromcfig("SERVER_INFO", 'DIRECTORY')
111
if (res[0] == 0):
112
print res[1]
113
raw_input()
114
sys.exit()
115
else:
116
directory = res[1]
117
118
#get urlfile
119
res =
补充:Web开发 , Python ,