本文整理汇总了Python中kademlia.network.Server.listen方法的典型用法代码示例。如果您正苦于以下问题:Python Server.listen方法的具体用法?Python Server.listen怎么用?Python Server.listen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kademlia.network.Server
的用法示例。
在下文中一共展示了Server.listen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_custom_protocol
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
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...
server = Server()
server.listen(8469)
self.assertNotIsInstance(server.protocol, CoconutProtocol)
server.stop()
# ...but our custom server does.
husk_server = HuskServer()
husk_server.listen(8469)
self.assertIsInstance(husk_server.protocol, CoconutProtocol)
husk_server.stop()
示例2: test_get
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
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
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
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: test_default_protocol
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
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()
示例5: KademliaUser
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
class KademliaUser(Runnable):
"""Allows the KademliaUser to be run in its own thread."""
def __init__(self, name="KademliaUser%d"%random.randint(1, 1000),
port=emu_config.kademlia_default_port, peerlist=None):
super(KademliaUser, self).__init__(name=name)
self.kademliaServer = Server()
self.port = port
self.peerlist = peerlist if peerlist is not None else []
def start(self):
"""Implements start() from the superclass."""
self._startKademlia()
try:
IOLoop.current().start()
except socket.error as ex:
logging.warning("Could not start the KademliaUser: %s"%ex)
def _startKademlia(self):
possible_interfaces = [iface for iface in netifaces.interfaces() if iface_searchterm in iface
and netifaces.ifaddresses(iface).has_key(netifaces.AF_INET)]
if len(possible_interfaces) == 0:
logging.error("No suitable interfaces found, tried the following: %s"%netifaces.interfaces())
logging.debug("Interfaces: %s"%netifaces.ifaddresses(possible_interfaces[0]))
ipAddr = netifaces.ifaddresses(possible_interfaces[0])[netifaces.AF_INET][0]["addr"]
logging.debug("Node %s starts with %s on %s"%(self.name, self.peerlist, ipAddr))
self.kademliaServer.listen(self.port, interface=ipAddr)
serverDeferred = self.kademliaServer.bootstrap([(peer, emu_config.kademlia_default_port) for peer in self.peerlist])
serverDeferred.addCallback(self.executeBot)
serverDeferred.addErrback(self.errback)
def executeBot(self, peersfound=None):
"""Method that is called regularly and checks for new commands"""
self.kademliaServer.get(generateRandomString(length=2)).addCallbacks(self.ignoreInput, self.errback)
self.kademliaServer.set(generateRandomString(length=2), generateRandomString()).addCallbacks(self.ignoreInput,
self.errback)
reactor.callLater(emu_config.botcommand_timeout, self.executeBot)
def ignoreInput(self, *args, **kwargs):
"""Gets whatever is the result of the Kademlia GET request and ignores it"""
pass
def errback(self, failure, *args, **kwargs):
"""Given to defereds to report errors. Ignores those errors."""
logging.debug(
"Kademlia Error (for the legitimate user, so non-existing keys are not a problem) in %s: %s"%(self.name, failure))
pass
示例6: dht_init
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
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)
示例7: uat
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
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
示例8: bootstrap_node
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
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()
示例9: getKey
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
def getKey(ip,port,key):
def done(result):
print "Key result:"
print 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([(ip, port)]).addCallback(bootstrapDone, server, key)
reactor.run()
示例10: helper
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
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()
示例11: setUp
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
def setUp(self):
# create peers
self.swarm = []
for i in range(TEST_SWARM_SIZE):
peer = Server()
bootstrap_peers = [
("127.0.0.1", PORT + x) for x in range(i)
][-1:] # each peer only knows of the last peer
peer.bootstrap(bootstrap_peers)
peer.listen(PORT + i)
self.swarm.append(peer)
# stabalize network overlay
time.sleep(10)
for peer in self.swarm:
peer.bootstrap(peer.bootstrappableNeighbors())
time.sleep(10)
for peer in self.swarm:
peer.bootstrap(peer.bootstrappableNeighbors())
time.sleep(10)
示例12: __init__
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
class BitHaikuDHT:
log = logging.getLogger(__name__)
def __init__(self, configuration):
self.configuration = configuration
self.server = Server()
self.server.listen(configuration.ports.dht)
self.server.bootstrap([(configuration.local_address, configuration.ports.dht)])
def add(self, ip):
self.log.error("Bootstrapping " + ip)
self.server.bootstrap([(ip, self.configuration.ports.dht)])
def find_owner(self, data):
key = value = hashlib.sha256(data).hexdigest()
self.server.set(key, value)
digest = kademlia.utils.digest(hash)
node = Node(digest)
nearest = self.server.protocol.router.findNeighbors(node)
return nearest[0].ip
示例13: test_default_protocol
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
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()
示例14: NetworkInterface
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
#.........这里部分代码省略.........
application = service.Application("kademlia")
application.setComponent(ILogObserver, log.FileLogObserver(sys.stdout, log.INFO).emit)
if os.path.isfile('cache.pickle'):
kserver = Server.loadState('cache.pickle')
else:
kserver = Server()
kserver.bootstrap([("127.0.0.1", port)])
kserver.saveStateRegularly('cache.pickle', 10)
server = internet.UDPServer(8468, kserver.protocol)
server.setServiceParent(application)
def connect(self, port):
if(self._app_deployer):
from twisted.application import service, internet
from twisted.python.log import ILogObserver
from twisted.internet import reactor, task
import sys, os
sys.path.append(os.path.dirname(__file__))
from kademlia.network import Server
from kademlia import log
application = service.Application("kademlia")
application.setComponent(ILogObserver, log.FileLogObserver(sys.stdout, log.INFO).emit)
if os.path.isfile('cache.pickle'):
kserver = Server.loadState('cache.pickle')
else:
kserver = Server()
kserver.bootstrap([("127.0.0.1", port)])
kserver.saveStateRegularly('cache.pickle', 10)
server = internet.UDPServer(8468, kserver.protocol)
server.setServiceParent(application)
def connect(self, port):
if(self._app_deployer):
from twisted.application import service, internet
from twisted.python.log import ILogObserver
from twisted.internet import reactor, task
import sys, os
sys.path.append(os.path.dirname(__file__))
from kademlia.network import Server
from kademlia import log
application = service.Application("kademlia")
application.setComponent(ILogObserver, log.FileLogObserver(sys.stdout, log.INFO).emit)
if os.path.isfile('cache.pickle'):
kserver = Server.loadState('cache.pickle')
else:
kserver = Server()
kserver.bootstrap([("127.0.0.1", port)])
kserver.saveStateRegularly('cache.pickle', 10)
server = internet.UDPServer(8468, kserver.protocol)
server.setServiceParent(application)
def bootStrapDone(self, server):
print self
print server
contacts = self.inetVisibleIP()
print contacts
def connect(self, port):
if(self._app_deployer):
from twisted.application import service, internet
from twisted.python.log import ILogObserver
from twisted.internet import reactor, task
import sys, os
sys.path.append(os.path.dirname(__file__))
from kademlia.network import Server
from kademlia import log
application = service.Application("kademlia")
application.setComponent(ILogObserver, log.FileLogObserver(sys.stdout, log.INFO).emit)
if os.path.isfile('cache.pickle'):
kserver = Server.loadState('cache.pickle')
else:
kserver = Server()
kserver.bootstrap([("127.0.0.1", port)])
kserver.saveStateRegularly('cache.pickle', 10)
server = internet.UDPServer(8468, kserver.protocol)
server.setServiceParent(application)
else:
self._node.listen(port)
self._node.bootstrap([("127.0.0.1",port)]).addCallback(self.bootStrapDone)
示例15: done
# 需要导入模块: from kademlia.network import Server [as 别名]
# 或者: from kademlia.network.Server import listen [as 别名]
hold_display = None
from storage import BlockStorage
def done(result):
print "Key result: ", result
print "Found: ", hold_display
reactor.stop()
def get_key(result, server):
global key, value
server.get(key).addCallback(done)
def set_key(found, server):
global key, value, hold_display
hold_display = found
server.set(key, value).addCallback(get_key, server)
server = Server(storage=BlockStorage())
server.listen(8467)
server.bootstrap([("127.0.0.1", 8468)]).addCallback(set_key, server)
reactor.run()