本文整理汇总了Python中network.Network.start方法的典型用法代码示例。如果您正苦于以下问题:Python Network.start方法的具体用法?Python Network.start怎么用?Python Network.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类network.Network
的用法示例。
在下文中一共展示了Network.start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: NetworkServer
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class NetworkServer(util.DaemonThread):
def __init__(self, config):
util.DaemonThread.__init__(self)
self.debug = False
self.config = config
self.pipe = util.QueuePipe()
self.network = Network(self.pipe, config)
self.lock = threading.RLock()
# each GUI is a client of the daemon
self.clients = []
self.request_id = 0
self.requests = {}
def add_client(self, client):
for key in ['status', 'banner', 'updated', 'servers', 'interfaces']:
value = self.network.get_status_value(key)
client.response_queue.put({'method':'network.status', 'params':[key, value]})
with self.lock:
self.clients.append(client)
print_error("new client:", len(self.clients))
def remove_client(self, client):
with self.lock:
self.clients.remove(client)
print_error("client quit:", len(self.clients))
def send_request(self, client, request):
with self.lock:
self.request_id += 1
self.requests[self.request_id] = (request['id'], client)
request['id'] = self.request_id
if self.debug:
print_error("-->", request)
self.pipe.send(request)
def run(self):
self.network.start()
while self.is_running():
try:
response = self.pipe.get()
except util.timeout:
continue
if self.debug:
print_error("<--", response)
response_id = response.get('id')
if response_id:
with self.lock:
client_id, client = self.requests.pop(response_id)
response['id'] = client_id
client.response_queue.put(response)
else:
# notification
m = response.get('method')
v = response.get('params')
for client in self.clients:
if m == 'network.status' or v in client.subscriptions.get(m, []):
client.response_queue.put(response)
self.network.stop()
print_error("server exiting")
示例2: NetworkServer
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class NetworkServer(threading.Thread):
def __init__(self, config):
threading.Thread.__init__(self)
self.daemon = True
self.config = config
self.network = Network(config)
# network sends responses on that queue
self.network_queue = Queue.Queue()
self.running = False
self.lock = threading.RLock()
# each GUI is a client of the daemon
self.clients = []
# todo: the daemon needs to know which client subscribed to which address
def is_running(self):
with self.lock:
return self.running
def stop(self):
with self.lock:
self.running = False
def start(self):
self.running = True
threading.Thread.start(self)
def add_client(self, client):
for key in ['status','banner','updated','servers','interfaces']:
value = self.network.get_status_value(key)
client.daemon_pipe.get_queue.put({'method':'network.status', 'params':[key, value]})
with self.lock:
self.clients.append(client)
def remove_client(self, client):
with self.lock:
self.clients.remove(client)
print_error("client quit:", len(self.clients))
def run(self):
self.network.start(self.network_queue)
while self.is_running():
try:
response = self.network_queue.get(timeout=0.1)
except Queue.Empty:
continue
for client in self.clients:
client.daemon_pipe.get_queue.put(response)
self.network.stop()
print_error("server exiting")
示例3: test_connect
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
def test_connect(self):
port1 = random.randint(20000, 30000)
port2 = random.randint(20000, 30000)
n1 = Network(port1)
n2 = Network(port2)
n1.start()
n2.start()
time.sleep(WAIT_TIME)
m = 'hasdgbaeswbjf'
n2.set_clipboard(m)
time.sleep(WAIT_TIME)
n1.connect('localhost', port2)
time.sleep(WAIT_TIME)
self.assertEqual(m, n1.get_clipboard())
n1.stop()
n2.stop()
示例4: __init__
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
def __init__(self, config):
network = Network(config)
if not network.start(wait=True):
print_msg("Not connected, aborting.")
sys.exit(1)
self.network = network
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind(('', 8000))
self.server.listen(5)
self.server.settimeout(1)
self.running = False
self.timeout = 60
示例5: NetworkProxy
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class NetworkProxy(threading.Thread):
def __init__(self, socket, config=None):
if config is None:
config = {} # Do not use mutables as default arguments!
threading.Thread.__init__(self)
self.config = SimpleConfig(config) if type(config) == type({}) else config
self.message_id = 0
self.unanswered_requests = {}
self.subscriptions = {}
self.debug = False
self.lock = threading.Lock()
self.pending_transactions_for_notifications = []
self.callbacks = {}
self.running = True
self.daemon = True
if socket:
self.pipe = util.SocketPipe(socket)
self.network = None
else:
self.network = Network(config)
self.pipe = util.QueuePipe(send_queue=self.network.requests_queue)
self.network.start(self.pipe.get_queue)
for key in ['status', 'banner', 'updated', 'servers', 'interfaces']:
value = self.network.get_status_value(key)
self.pipe.get_queue.put({'method': 'network.status', 'params': [key, value]})
# status variables
self.status = 'connecting'
self.servers = {}
self.banner = ''
self.blockchain_height = 0
self.server_height = 0
self.interfaces = []
def is_running(self):
return self.running
def run(self):
while self.is_running():
try:
response = self.pipe.get()
except util.timeout:
continue
if response is None:
break
self.process(response)
self.trigger_callback('stop')
if self.network:
self.network.stop()
print_error("NetworkProxy: terminating")
def process(self, response):
if self.debug:
print_error("<--", response)
if response.get('method') == 'network.status':
key, value = response.get('params')
if key == 'status':
self.status = value
elif key == 'banner':
self.banner = value
elif key == 'updated':
self.blockchain_height, self.server_height = value
elif key == 'servers':
self.servers = value
elif key == 'interfaces':
self.interfaces = value
self.trigger_callback(key)
return
msg_id = response.get('id')
result = response.get('result')
error = response.get('error')
if msg_id is not None:
with self.lock:
method, params, callback = self.unanswered_requests.pop(msg_id)
else:
method = response.get('method')
params = response.get('params')
with self.lock:
for k, v in self.subscriptions.items():
if (method, params) in v:
callback = k
break
else:
print_error("received unexpected notification", method, params)
return
r = {'method':method, 'params':params, 'result':result, 'id':msg_id, 'error':error}
callback(r)
def send(self, messages, callback):
"""return the ids of the requests that we sent"""
# detect subscriptions
sub = []
#.........这里部分代码省略.........
示例6: NetworkProxy
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class NetworkProxy(util.DaemonThread):
def __init__(self, socket, config=None):
if config is None:
config = {} # Do not use mutables as default arguments!
util.DaemonThread.__init__(self)
self.config = SimpleConfig(config) if type(config) == type({}) else config
self.message_id = 0
self.unanswered_requests = {}
self.subscriptions = {}
self.debug = False
self.lock = threading.Lock()
self.callbacks = {}
if socket:
self.pipe = util.SocketPipe(socket)
self.network = None
else:
self.pipe = util.QueuePipe()
self.network = Network(self.pipe, config)
self.network.start()
for key in ['fee','status','banner','updated','servers','interfaces']:
value = self.network.get_status_value(key)
self.pipe.get_queue.put({'method':'network.status', 'params':[key, value]})
# status variables
self.status = 'unknown'
self.servers = {}
self.banner = ''
self.blockchain_height = 0
self.server_height = 0
self.interfaces = []
# value returned by estimatefee
self.fee = None
def run(self):
while self.is_running():
self.run_jobs() # Synchronizer and Verifier
try:
response = self.pipe.get()
except util.timeout:
continue
if response is None:
break
# Protect against ill-formed or malicious server responses
try:
self.process(response)
except:
traceback.print_exc(file=sys.stderr)
self.trigger_callback('stop')
if self.network:
self.network.stop()
self.print_error("stopped")
def process(self, response):
if self.debug:
self.print_error("<--", response)
if response.get('method') == 'network.status':
key, value = response.get('params')
if key == 'status':
self.status = value
elif key == 'banner':
self.banner = value
elif key == 'fee':
self.fee = value
elif key == 'updated':
self.blockchain_height, self.server_height = value
elif key == 'servers':
self.servers = value
elif key == 'interfaces':
self.interfaces = value
if key in ['status', 'updated']:
self.trigger_callback(key)
else:
self.trigger_callback(key, (value,))
return
msg_id = response.get('id')
result = response.get('result')
error = response.get('error')
if msg_id is not None:
with self.lock:
method, params, callback = self.unanswered_requests.pop(msg_id)
else:
method = response.get('method')
params = response.get('params')
with self.lock:
for k,v in self.subscriptions.items():
if (method, params) in v:
callback = k
break
else:
self.print_error("received unexpected notification",
method, params)
return
r = {'method':method, 'params':params, 'result':result,
#.........这里部分代码省略.........
示例7: NetworkProxy
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class NetworkProxy(util.DaemonThread):
def __init__(self, socket, config=None):
if config is None:
config = {} # Do not use mutables as default arguments!
util.DaemonThread.__init__(self)
self.config = SimpleConfig(config) if type(config) == type({}) else config
self.message_id = 0
self.unanswered_requests = {}
self.subscriptions = {}
self.debug = False
self.lock = threading.Lock()
self.callbacks = {}
if socket:
self.pipe = util.SocketPipe(socket)
self.network = None
else:
self.pipe = util.QueuePipe()
self.network = Network(self.pipe, config)
self.network.start()
for key in ["fee", "status", "banner", "updated", "servers", "interfaces"]:
value = self.network.get_status_value(key)
self.pipe.get_queue.put({"method": "network.status", "params": [key, value]})
# status variables
self.status = "unknown"
self.servers = {}
self.banner = ""
self.blockchain_height = 0
self.server_height = 0
self.interfaces = []
self.jobs = []
# value returned by estimatefee
self.fee = None
def run(self):
while self.is_running():
for job in self.jobs:
job()
try:
response = self.pipe.get()
except util.timeout:
continue
if response is None:
break
self.process(response)
self.trigger_callback("stop")
if self.network:
self.network.stop()
self.print_error("stopped")
def process(self, response):
if self.debug:
print_error("<--", response)
if response.get("method") == "network.status":
key, value = response.get("params")
if key == "status":
self.status = value
elif key == "banner":
self.banner = value
elif key == "fee":
self.fee = value
elif key == "updated":
self.blockchain_height, self.server_height = value
elif key == "servers":
self.servers = value
elif key == "interfaces":
self.interfaces = value
if key in ["status", "updated"]:
self.trigger_callback(key)
else:
self.trigger_callback(key, (value,))
return
msg_id = response.get("id")
result = response.get("result")
error = response.get("error")
if msg_id is not None:
with self.lock:
method, params, callback = self.unanswered_requests.pop(msg_id)
else:
method = response.get("method")
params = response.get("params")
with self.lock:
for k, v in self.subscriptions.items():
if (method, params) in v:
callback = k
break
else:
print_error("received unexpected notification", method, params)
return
r = {"method": method, "params": params, "result": result, "id": msg_id, "error": error}
callback(r)
def send(self, messages, callback):
"""return the ids of the requests that we sent"""
#.........这里部分代码省略.........
示例8: __init__
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class NetworkServer:
def __init__(self, config):
self.network = Network(config)
self.network.trigger_callback = self.trigger_callback
self.network.start()
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.daemon_port = config.get('daemon_port', DAEMON_PORT)
self.socket.bind(('', self.daemon_port))
self.socket.listen(5)
self.socket.settimeout(1)
self.running = False
# daemon terminates after period of inactivity
self.timeout = config.get('daemon_timeout', 5*60)
self.lock = threading.RLock()
# each GUI is a client of the daemon
self.clients = []
# daemon needs to know which client subscribed to which address
def stop(self):
with self.lock:
self.running = False
def add_client(self, client):
for key in ['status','banner','updated','servers','interfaces']:
value = self.get_status_value(key)
client.queue.put({'method':'network.status', 'params':[key, value]})
with self.lock:
self.clients.append(client)
def remove_client(self, client):
with self.lock:
self.clients.remove(client)
print_error("client quit:", len(self.clients))
def get_status_value(self, key):
if key == 'status':
value = self.network.connection_status
elif key == 'banner':
value = self.network.banner
elif key == 'updated':
value = (self.network.get_local_height(), self.network.get_server_height())
elif key == 'servers':
value = self.network.get_servers()
elif key == 'interfaces':
value = self.network.get_interfaces()
return value
def trigger_callback(self, key):
value = self.get_status_value(key)
print_error("daemon trigger callback", key, len(self.clients))
for client in self.clients:
client.queue.put({'method':'network.status', 'params':[key, value]})
def main_loop(self):
self.running = True
t = time.time()
while self.running:
try:
connection, address = self.socket.accept()
except socket.timeout:
if not self.clients:
if time.time() - t > self.timeout:
print_error("Daemon timeout")
break
else:
t = time.time()
continue
t = time.time()
client = ClientThread(self, self.network, connection)
client.start()
print_error("Daemon exiting")
示例9: Daemon
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class Daemon(DaemonThread):
def __init__(self, config, fd):
DaemonThread.__init__(self)
self.config = config
if config.get("offline"):
self.network = None
else:
self.network = Network(config)
self.network.start()
self.gui = None
self.wallets = {}
# Setup server
cmd_runner = Commands(self.config, None, self.network)
host = config.get("rpchost", "localhost")
port = config.get("rpcport", 0)
server = SimpleJSONRPCServer((host, port), logRequests=False, requestHandler=RequestHandler)
os.write(fd, repr((server.socket.getsockname(), time.time())))
os.close(fd)
server.timeout = 0.1
for cmdname in known_commands:
server.register_function(getattr(cmd_runner, cmdname), cmdname)
server.register_function(self.run_cmdline, "run_cmdline")
server.register_function(self.ping, "ping")
server.register_function(self.run_daemon, "daemon")
server.register_function(self.run_gui, "gui")
self.server = server
def ping(self):
return True
def run_daemon(self, config):
sub = config.get("subcommand")
assert sub in ["start", "stop", "status"]
if sub == "start":
response = "Daemon already running"
elif sub == "status":
if self.network:
p = self.network.get_parameters()
response = {
"path": self.network.config.path,
"server": p[0],
"blockchain_height": self.network.get_local_height(),
"server_height": self.network.get_server_height(),
"nodes": self.network.get_interfaces(),
"connected": self.network.is_connected(),
"auto_connect": p[4],
"wallets": {k: w.is_up_to_date() for k, w in self.wallets.items()},
}
else:
response = "Daemon offline"
elif sub == "stop":
self.stop()
response = "Daemon stopped"
return response
def run_gui(self, config_options):
config = SimpleConfig(config_options)
if self.gui:
if hasattr(self.gui, "new_window"):
path = config.get_wallet_path()
self.gui.new_window(path, config.get("url"))
response = "ok"
else:
response = "error: current GUI does not support multiple windows"
else:
response = "Error: Electrum is running in daemon mode. Please stop the daemon first."
return response
def load_wallet(self, path, get_wizard=None):
if path in self.wallets:
wallet = self.wallets[path]
else:
storage = WalletStorage(path)
if get_wizard:
if storage.file_exists:
wallet = Wallet(storage)
action = wallet.get_action()
else:
action = "new"
if action:
wizard = get_wizard()
wallet = wizard.run(self.network, storage)
else:
wallet.start_threads(self.network)
else:
wallet = Wallet(storage)
wallet.start_threads(self.network)
if wallet:
self.wallets[path] = wallet
return wallet
def run_cmdline(self, config_options):
config = SimpleConfig(config_options)
cmdname = config.get("cmd")
cmd = known_commands[cmdname]
path = config.get_wallet_path()
wallet = self.load_wallet(path) if cmd.requires_wallet else None
# arguments passed to function
args = map(lambda x: config.get(x), cmd.params)
#.........这里部分代码省略.........
示例10: main
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
def main(args):
config.SHOULD_LOG = args.log
topo = topology.parse_topology(args.topo)
print "\n"
print "########################################"
print "# SIMULATION PARAMETERS. #"
print "########################################"
pprint(args.__dict__)
print "\n"
print "########################################"
print "# TOPOLOGY. #"
print "########################################"
pprint(topo)
print "\n"
print "########################################"
print "# SIMULATION LOG. #"
print "########################################"
# Set up nodes in the network.
nodes = {}
network = Network(delay=args.delay, loss=args.loss)
for addr, outgoing_links in topo:
node = Node.create(addr)
nodes[addr] = node
network.add_node(node, outgoing_links)
# Start the network.
network.start()
# Run protocol.
APP_CLS = PROTOCOLS[args.protocol]
for addr, node in nodes.iteritems():
node.start_application(APP_CLS(addr))
if args.protocol == 'pong':
for addr in args.seed:
nodes[addr].get_application(APP_CLS.ADDRESS).send_ping()
nodes[addr].get_application(APP_CLS.ADDRESS).send_time_set()
if args.protocol == 'make':
assert args.target
for addr in args.seed:
nodes[addr].get_application(APP_CLS.ADDRESS).set_mode(app.pong.Mode.MAKE)
nodes[addr].get_application(APP_CLS.ADDRESS).send_make_flood(args.target)
if args.protocol == 'toporeq':
for addr in args.seed:
nodes[addr].get_application(APP_CLS.ADDRESS).send_topo_req()
if args.protocol == 'topoflood':
for addr in args.seed:
nodes[addr].get_application(APP_CLS.ADDRESS).send_topo_flood()
if args.protocol == 'deluge' or args.protocol == 'rateless':
for addr, node in nodes.iteritems():
application = node.get_application(APP_CLS.ADDRESS)
application.stop_protocol()
application.protocol.K = args.k
application.protocol.T_MIN = args.tmin
application.protocol.T_MAX = args.tmax
application.protocol.FRAME_DELAY = args.framedelay
application.protocol.T_R = args.t_r
application.protocol.T_TX = args.t_tx
application.protocol.W = args.w
application.protocol.RX_MAX = args.rx_max
if args.protocol == 'deluge':
assert args.dpagesize % args.dpacketsize == 0
application.protocol.PAGE_SIZE = args.dpagesize
application.protocol.PACKET_SIZE = args.dpacketsize
application.protocol.PACKETS_PER_PAGE = args.dpagesize / args.dpacketsize
elif args.protocol == 'rateless':
assert args.rpagesize % args.rpacketsize == 0
application.protocol.PAGE_SIZE = args.rpagesize
application.protocol.PACKET_SIZE = args.rpacketsize
application.protocol.PACKETS_PER_PAGE = args.rpagesize / args.rpacketsize
application.protocol.PDU_CLS.DATA_FORMAT = "II" + ("B" * application.protocol.PACKETS_PER_PAGE) + \
("B" * application.protocol.PACKET_SIZE)
# TODO: Cleaner way to do this.
app.protocol.rateless_deluge.ROWS_REQUIRED = args.rpagesize / args.rpacketsize
application.start_protocol()
# Read file and seed in the network.
data = args.file.read()
args.file.close()
for addr in args.seed:
nodes[addr].get_application(APP_CLS.ADDRESS).disseminate(data)
# Don't terminate.
while True:
time.sleep(100)
示例11: NetworkProxy
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class NetworkProxy(util.DaemonThread):
"""Proxy for communicating with the daemon or Network.
If the daemon is running when this is initialized,
this will create a socket pipe.
Otherwise, this will create a new Network instance."""
def __init__(self, socket, config=None):
if config is None:
config = {} # Do not use mutables as default arguments!
util.DaemonThread.__init__(self)
self.config = SimpleConfig(config) if type(config) == type({}) else config
self.message_id = 0
self.unanswered_requests = {}
self.subscriptions = {}
self.debug = False
self.lock = threading.Lock()
self.pending_transactions_for_notifications = []
self.callbacks = {}
if socket:
self.pipe = util.SocketPipe(socket)
self.network = None
else:
self.pipe = util.QueuePipe()
self.network = Network(self.pipe, config)
self.network.start()
for key in ['status','banner','updated','servers','interfaces']:
value = self.network.get_status_value(key)
self.pipe.get_queue.put({'method':'network.status', 'params':[key, value]})
# status variables
self.status = 'connecting'
self.servers = {}
self.banner = ''
self.blockchain_height = 0
self.server_height = 0
self.interfaces = []
def switch_to_active_chain(self):
"""Create a new Network instance or send message to daemon."""
with self.lock:
# for the network.switch_chains request
message_id = self.message_id
self.message_id = 0
self.unanswered_requests = {}
self.subscriptions = {}
self.pending_transactions_for_notifications = []
self.callbacks = {}
self.status = 'connecting'
self.servers = {}
self.banner = ''
self.blockchain_height = 0
self.server_height = 0
self.interfaces = []
# Not daemon, probably running GUI
if self.network:
self.network.switch_chains()
for key in ['status','banner','updated','servers','interfaces']:
value = self.network.get_status_value(key)
self.pipe.get_queue.put({'method':'network.status', 'params':[key, value]})
# Daemon is running
else:
req = {'id': message_id, 'method': 'network.switch_chains', 'params':[chainparams.get_active_chain().code]}
self.pipe.send(req)
def run(self):
while self.is_running():
try:
response = self.pipe.get()
except util.timeout:
continue
if response is None:
break
self.process(response)
self.trigger_callback('stop')
if self.network:
self.network.stop()
self.print_error("stopped")
def process(self, response):
if self.debug:
print_error("<--", response)
if response.get('method') == 'network.status':
key, value = response.get('params')
if key == 'status':
self.status = value
elif key == 'banner':
self.banner = value
elif key == 'updated':
self.blockchain_height, self.server_height = value
elif key == 'servers':
#.........这里部分代码省略.........
示例12: NetworkServer
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class NetworkServer(util.DaemonThread):
"""Server that the daemon sends connections to.
Handles requests/responses to/from the Network
from ClientThreads. Also handles notifying
ClientThreads of responses to their subscriptions."""
def __init__(self, config):
util.DaemonThread.__init__(self)
self.debug = False
self.config = config
self.pipe = util.QueuePipe()
self.network = Network(self.pipe, config)
self.lock = threading.RLock()
# each GUI is a client of the daemon
self.clients = []
self.request_id = 0
# dict of {request_id: client}
self.requests = {}
def add_client(self, client):
for key in ['status', 'banner', 'updated', 'servers', 'interfaces']:
value = self.network.get_status_value(key)
client.response_queue.put({'method':'network.status', 'params':[key, value]})
with self.lock:
self.clients.append(client)
print_error("new client:", len(self.clients))
def remove_client(self, client):
with self.lock:
self.clients.remove(client)
print_error("client quit:", len(self.clients))
def send_request(self, client, request):
with self.lock:
self.request_id += 1
self.requests[self.request_id] = (request['id'], client)
request['id'] = self.request_id
if self.debug:
print_error("-->", request)
self.pipe.send(request)
def run(self):
self.network.start()
while self.is_running():
try:
response = self.pipe.get()
except util.timeout:
continue
if self.debug:
print_error("<--", response)
response_id = response.get('id')
if response_id:
with self.lock:
client_id, client = self.requests.pop(response_id)
response['id'] = client_id
client.response_queue.put(response)
else:
# responses with no id are notifications (e.g. to subscriptions)
# and are sent to whichever clients have the subscription.
m = response.get('method')
v = response.get('params')
for client in self.clients:
if repr((m, v)) in client.subscriptions or m == 'network.status':
client.response_queue.put(response)
self.network.stop()
print_error("server exiting")
示例13: __init__
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class Session:
def __init__(self):
# TODO: consider saving and loading the connections list to a file
# to preserve the list between sessions
self._con_mgr = ConnectionManager()
# The data on the common clipboard.
self._clipboard_data = None
# Type of data on the clipboard (eg. text, bitmap, etc.)
# This should be one of the supported types in info.py
self._data_type = None
# None will mean that this client is owner, otherwise it should be a
# Connection object.
self._data_owner = None
# TODO add command line switch to change port, which would be passed in
# here
self._network = Network(con_callback=self._new_connection_request,
dis_callback=self._disconnect_request)
self._network.start()
def _new_connection_request(self, address, port):
conn = self._con_mgr.get_connection(address)
if conn:
#conn.status = Connection.REQUEST
conn.status = Connection.CONNECTED
else:
#self._con_mgr.new_connection("", address, Connection.REQUEST)
self._con_mgr.new_connection("", address, Connection.CONNECTED)
def _disconnect_request(self, address, port):
conn = self._con_mgr.get_connection(address)
if conn:
conn.status = Connection.NOT_CONNECTED
def get_clipboard_data(self):
self._clipboard_data = self._network.get_clipboard()
return self._clipboard_data
def get_clipboard_data_type(self):
self._data_type = self._network.get_clipboard_data_type()
return self._data_type
def get_clipboard_data_owner(self):
return self._data_owner
def set_clipboard_data(self, data, data_type):
"""
This is called (by the gui) when the user pastes to the app.
"""
self._clipboard_data = data
self._network.set_clipboard(self._clipboard_data)
self._data_type = data_type
self._data_owner = None
def connections(self):
"""
Returns a list of all the connections
"""
return self._con_mgr.connections
def get_connection(self, address):
"""
Returns the Connection object that has the given address
"""
return self._con_mgr.get_connection(address)
def new_connection(self, alias, address):
"""
Creates a new Connection to the given address and if there is
a Syncboard app running at that address then that user will
see a new connection appear (with the address on this end) with
status REQUEST.
After this has executed:
New Connection on both ends.
Connection on this end status: PENDING
Conneciton on other end status: REQUEST
"""
self._network.connect(address)
self._con_mgr.new_connection(alias, address)
def accept_connection(self, address):
"""
Called when the user accepts the request from the Connection with
the given address. Meaning, there was a Connection with status
REQUEST and user accepted it.
Before this is called:
Connection on this end status: REQUEST
Conneciton on other end status: PENDING
After this has executed:
Connection on this end status: CONNECTED
Conneciton on other end status: CONNECTED
"""
conn = self.get_connection(address)
if conn:
print "Connection from %s accepted" % address
conn.status = Connection.CONNECTED
#.........这里部分代码省略.........
示例14: TestSimple
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class TestSimple(unittest.TestCase):
def setUp(self):
self.port1 = random.randint(20000, 30000)
self.port2 = random.randint(20000, 30000)
self.n1 = Network(self.port1)
self.n2 = Network(self.port2)
self.n1.start()
self.n2.start()
# give everything time to get going
time.sleep(WAIT_TIME)
# establish connection
self.n2.connect('localhost', self.port1)
time.sleep(WAIT_TIME)
# test simple clipboard syncing
def test_simple(self):
m1 = 'test 1'
self.n2.set_clipboard(m1)
time.sleep(WAIT_TIME)
self.assertEqual(self.n1.get_clipboard(), m1)
m2 = 'test 2'
self.n1.set_clipboard(m2)
time.sleep(WAIT_TIME)
self.assertEqual(self.n2.get_clipboard(), m2)
def test_disconnect_from_client(self):
self.n2.set_clipboard('test')
time.sleep(WAIT_TIME)
self.assertEqual(self.n1.get_clipboard(), 'test')
self.n2.disconnect('localhost')
time.sleep(WAIT_TIME)
m = "test %d" % random.randint(0, 1000)
self.n2.set_clipboard(m)
time.sleep(WAIT_TIME)
self.assertNotEqual(self.n1.get_clipboard(), m)
def test_disconnect_from_server(self):
self.n2.set_clipboard('test')
time.sleep(WAIT_TIME)
self.assertEqual(self.n1.get_clipboard(), 'test')
self.n1.disconnect('localhost')
time.sleep(WAIT_TIME)
m = "test %d" % random.randint(0, 1000)
self.n2.set_clipboard(m)
time.sleep(WAIT_TIME)
self.assertNotEqual(self.n1.get_clipboard(), m)
def test_reconnect(self):
self.n2.disconnect('localhost')
time.sleep(WAIT_TIME)
self.n1.connect('localhost', self.port2)
time.sleep(WAIT_TIME)
self.n1.set_clipboard('asdf 5')
time.sleep(WAIT_TIME)
self.assertEqual(self.n2.get_clipboard(), 'asdf 5')
def tearDown(self):
# give it enough time to execute before tearing down
time.sleep(WAIT_TIME)
self.n1.stop()
self.n2.stop()
示例15: NetworkServer
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import start [as 别名]
class NetworkServer(threading.Thread):
def __init__(self, config):
threading.Thread.__init__(self)
self.daemon = True
self.debug = False
self.config = config
self.network = Network(config)
# network sends responses on that queue
self.network_queue = Queue.Queue()
self.running = False
self.lock = threading.RLock()
# each GUI is a client of the daemon
self.clients = []
self.request_id = 0
self.requests = {}
def is_running(self):
with self.lock:
return self.running
def stop(self):
with self.lock:
self.running = False
def start(self):
self.running = True
threading.Thread.start(self)
def add_client(self, client):
for key in ['status','banner','updated','servers','interfaces']:
value = self.network.get_status_value(key)
client.response_queue.put({'method':'network.status', 'params':[key, value]})
with self.lock:
self.clients.append(client)
print_error("new client:", len(self.clients))
def remove_client(self, client):
with self.lock:
self.clients.remove(client)
print_error("client quit:", len(self.clients))
def send_request(self, client, request):
with self.lock:
self.request_id += 1
self.requests[self.request_id] = (request['id'], client)
request['id'] = self.request_id
if self.debug:
print_error("-->", request)
self.network.requests_queue.put(request)
def run(self):
self.network.start(self.network_queue)
while self.is_running():
try:
response = self.network_queue.get(timeout=0.1)
except Queue.Empty:
continue
if self.debug:
print_error("<--", response)
response_id = response.get('id')
if response_id:
with self.lock:
client_id, client = self.requests.pop(response_id)
response['id'] = client_id
client.response_queue.put(response)
else:
# notification
for client in self.clients:
client.response_queue.put(response)
self.network.stop()
print_error("server exiting")