本文整理汇总了Python中kademlia.network.Server类的典型用法代码示例。如果您正苦于以下问题:Python Server类的具体用法?Python Server怎么用?Python Server使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Server类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_custom_protocol
def test_custom_protocol(self):
"""
A subclass of Server which overrides the protocol_class attribute will
have an instance of that class as its protocol after its listen()
method is called.
"""
# Make a custom Protocol and Server to go with hit.
class CoconutProtocol(KademliaProtocol):
pass
class HuskServer(Server):
protocol_class = CoconutProtocol
# An ordinary server does NOT have a CoconutProtocol as its protocol...
loop = asyncio.get_event_loop()
server = Server()
loop.run_until_complete(server.listen(8469))
self.assertNotIsInstance(server.protocol, CoconutProtocol)
server.stop()
# ...but our custom server does.
husk_server = HuskServer()
loop.run_until_complete(husk_server.listen(8469))
self.assertIsInstance(husk_server.protocol, CoconutProtocol)
husk_server.stop()
示例2: test_get
def test_get(self):
expected = "rohan"
key = "A"
# getkey("127.0.0.1",8468,key)
# self.assertEqual(expected,result)
def done(result):
# print "Key result:"
# print result
self.assertEqual(expected, result)
reactor.stop()
def bootstrapDone(found, server, key):
if len(found) == 0:
print "Could not connect to the bootstrap server."
reactor.stop()
server.get(key).addCallback(done)
server = Server()
temp_port = random.randint(9000, 9999)
server.listen(
temp_port
) # Any node wishing to query the network essentially registers itself as a server/node with every node it communicates with
server.bootstrap([("127.0.0.1", 8468)]).addCallback(bootstrapDone, server, key)
reactor.run()
示例3: refresh_mirror
def refresh_mirror( working_dir, first_block, last_block ):
"""
Refresh the mirror:
* process all new invalidations
* grab and mirror any new profiles from the DHT
This gets called by Twisted every time there ought to be a new block.
"""
from twisted.python import log
from kademlia.network import Server
# make soure our bitcoind cached block index is up-to-speed
nameop_sequence = sync_blockchain( working_dir, first_block, last_block )
if nameop_sequence is None:
log.error("sync_blockchain(%s-%s) failed" % (first_block, last_block))
return None
# synchronize name registrations...
server = Server()
server.listen( dht.plugin.DHT_SERVER_PORT )
server.bootstrap( dht.plugin.DEFAULT_DHT_SERVERS ).addCallback( connect_done, server )
pass
示例4: __init__
def __init__(self, config, bootstrapNeighbors):
if os.path.isfile(config['dht.state.cache']):
self.kserver = Server.loadState(config['dht.state.cache'])
else:
self.kserver = Server()
self.kserver.bootstrap(bootstrapNeighbors)
self.kserver.saveStateRegularly(config['dht.state.cache'], 60)
示例5: bootstrap_node
def bootstrap_node(event_loop):
server = Server()
event_loop.run_until_complete(server.listen(8468))
try:
yield ('127.0.0.1', 8468)
finally:
server.stop()
示例6: __init__
def __init__(self, ksize=20, alpha=3, id=None, storage=None):
storage = storage or ForgetfulStorageFix()
Server.__init__(self, ksize, alpha, id, storage=storage)
self.set_keys=set([])
self.protocol = KademliaProtocolAppend(self.node, self.storage, ksize, set_keys=self.set_keys)
if kademlia_version != '0.5':
_log.error("#################################################")
_log.error("### EXPECTING VERSION 0.5 of kademlia package ###")
_log.error("#################################################")
示例7: test_storing
async def test_storing(bootstrap_node):
server = Server()
await server.listen(bootstrap_node[1] + 1)
await server.bootstrap([bootstrap_node])
await server.set('key', 'value')
result = await server.get('key')
assert result == 'value'
server.stop()
示例8: test_default_protocol
def test_default_protocol(self):
"""
An ordinary Server object will initially not have a protocol, but will
have a KademliaProtocol object as its protocol after its listen()
method is called.
"""
server = Server()
self.assertIsNone(server.protocol)
server.listen(8469)
self.assertIsInstance(server.protocol, KademliaProtocol)
server.stop()
示例9: test_default_protocol
def test_default_protocol(self):
"""
An ordinary Server object will initially not have a protocol, but will
have a KademliaProtocol object as its protocol after its listen()
method is called.
"""
loop = asyncio.get_event_loop()
server = Server()
self.assertIsNone(server.protocol)
loop.run_until_complete(server.listen(8469))
self.assertIsInstance(server.protocol, KademliaProtocol)
server.stop()
示例10: DHTResolver
class DHTResolver(object):
def __init__(self, config, bootstrapNeighbors):
self.config = config
self.log = Logger(system=self)
if os.path.isfile(config['dht.state.cache']):
self.kserver = Server.loadState(config['dht.state.cache'])
else:
self.kserver = Server()
self.kserver.bootstrap(bootstrapNeighbors)
self.kserver.saveStateRegularly(config['dht.state.cache'], 60)
def getProtocol(self):
return self.kserver.protocol
def getPublicKey(self, keyId):
"""
Get the public key from the network, and return only if the key is
the one that matches the keyId based on hash.
"""
def verify(key):
if key is not None and PublicKey(key).getKeyId() == keyId:
return key
return None
self.log.debug("Getting key text for key id %s" % keyId)
return self.kserver.get(keyId).addCallback(verify)
def resolve(self, keyId):
def parse(locations):
self.log.debug("Locations for %s: %s" % (keyId, locations))
results = []
if locations is None or locations == "":
return results
for location in locations.split(','):
host, port = location.split(':')
results.append((host, int(port)))
return results
d = self.kserver.get("%s-location" % keyId)
return d.addCallback(parse)
def announceLocation(self, myKeyId, myPublicKey):
def announce(ips):
ips = self.localAddresses() + ips
ipports = map(lambda ip: "%s:%i" % (ip, self.config['s2s.port']), ips)
return self.kserver.set("%s-location" % myKeyId, ",".join(ipports))
d = self.kserver.set(myKeyId, str(myPublicKey))
d.addCallback(lambda _: self.kserver.inetVisibleIP())
return d.addCallback(announce)
def localAddresses(self):
result = []
for iface in netifaces.interfaces():
addys = netifaces.ifaddresses(iface).get(netifaces.AF_INET)
result += [ addy['addr'] for addy in (addys or []) if addy['addr'] != '127.0.0.1' ]
return result
示例11: dht_init
def dht_init(blockchain_index):
"""
Establish our connection to the DHT, and give
it the requisite state it needs (i.e. the index
over the blockchain).
"""
global dht_server
global dht_blockchain_index
dht_blockchain_index = blockchain_index
dht_server = Server(storage=BlockStorage())
dht_server.listen(DHT_SERVER_PORT)
bootstrap_servers = hostname_to_ip(DEFAULT_DHT_SERVERS)
dht_server.bootstrap(bootstrap_servers)
示例12: __init__
def __init__(self, name="app_default",port=4020):
self._name = name
self.number_of_nodes = 0
self.list_of_nodes = []
self._queues = [DeferredQueue()] * 3
# web process pointer
self._web = ""
# here is the logic to join the DHT, currently using an implementation of Kademlia
from entangled.kademlia import node
knownNodes = [("127.0.0.1", 4021)]
self._ip_address = "127.0.0.1"
#self._node = node.Node(4020)
#self._node.joinNetwork(knownNodes)
from kademlia.network import Server
self._serverNode = Server()
# listen on port 5556
self._serverNode.listen(5556)
# bootstrap with known nodes
self._serverNode.bootstrap([("127.0.0.1",5557)]).addCallback(self.bootStrapDone)
示例13: uat
def uat(wc, option_flags, option_format, myReason):
from twisted.internet import reactor
from twisted.python import log
from kademlia.network import Server
import sys
log.startLogging(sys.stdout)
def query(wc, query_string):
wc = wc.canonicalize()
query_string = "@prefix : <http://test#>.\n" + query_string
query_file = "query.tmp.n3"
o = open(query_file, "w")
o.write(query_string)
o.close()
filterContext = _store.load(query_file,
flags=option_flags[option_format],
referer="",
why=myReason, topLevel=True)
wc.reopen()
print "applying...", filterContext, "to", wc
applyRules(wc, filterContext);
return wc
def done(result):
print "Key result:", result
#reactor.stop()
def setDone(result, server):
server.get("a key").addCallback(done)
def kademliaBootstrapDone(found, server):
server.set("a key", "a value").addCallback(setDone, server)
server = Server()
server.listen(8468)
server.bootstrap([("1.2.3.4", 8468)]).addCallback(kademliaBootstrapDone, server)
wc = query(wc, "[ a :banana ].")
#reactor.run()
return wc
示例14: helper
def helper(file, ip, bootstrapPort, localPort, send, debug):
# No loss yet !
config.totalLoss = 0
config.debug = debug
# Start Server
if debug == 'loads': log.startLogging(sys.stdout)
server = Server()
# Start own server on port 5678
server.listen(localPort)
# Bootstrap with a known ip address of an existing kad server
server.bootstrap([(ip, bootstrapPort)]).addCallback(started, server, send, file, debug)
reactor.run()
示例15: __init__
def __init__(self, name="KademliaBot%d" % random.randint(1, 1000),
port=emu_config.kademlia_default_port, peerlist=None):
super(KademliaBot, self).__init__(name=name)
self.kademliaServer = Server()
handlers = [("/current_command", KademliaCommandHandler, {"kserver": self.kademliaServer})]
app = tornado.web.Application(handlers, autoreload=False)
self.httpserver = tornado.httpserver.HTTPServer(app)
self.port = port
self.peerlist = peerlist if peerlist is not None else []