本文整理汇总了Python中network.Network.connect方法的典型用法代码示例。如果您正苦于以下问题:Python Network.connect方法的具体用法?Python Network.connect怎么用?Python Network.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类network.Network
的用法示例。
在下文中一共展示了Network.connect方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Game
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import connect [as 别名]
class Game():
def __init__(self):
pygame.init()
# network
self.network = Network()
self.network.connect()
self.network.login(username)
netThread = threading.Thread(target=self.update_network)
netThread.start()
self.screen = pygame.display.set_mode((1024, 768), 0, 32)
self.load()
def load(self):
self.background = pygame.image.load(background_image_filename).convert()
self.image = pygame.image.load(sprite_image_filename).convert_alpha()
self.update()
def update(self):
global pos
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
if event.type == MOUSEBUTTONDOWN:
pos[0] += 5
self.draw()
def draw(self):
self.screen.blit(self.background, (0,0))
# network data draw
if network_received is not None:
for player in network_received:
sp = Sprite(self, sprite_image_filename)
sp.image = self.image
sp.position = Vector2(player['pos'][0], player['pos'][1])
sp.draw()
pygame.display.update()
def update_network(self):
global network_received
while True:
data = {'action': 'update', 'id': username, 'pos': pos}
network_received = json.loads(self.network.update(json.dumps(data)))
time.sleep(0.05)
示例2: SocketTest
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import connect [as 别名]
class SocketTest(unittest.TestCase):
def setUp(self):
self.network = Network()
# start two
self.q = Queue.Queue(maxsize=0)
self.node = []
self.node_1 = Node(0, self.q)
self.node.append(self.node_1)
self.node_2 = Node(1, self.q)
self.node.append(self.node_2)
for n in self.node:
t = threading.Thread(target=n.start)
t.daemon = True
t.start()
result = self.network.connect(n)
self.assertTrue(result)
def test_1(self):
self.assertEqual(len(self.network.node), 2)
def tearDown(self):
for node in self.node:
result = node.kill()
self.assertTrue(result)
示例3: test_connect
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import connect [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: Network
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import connect [as 别名]
N_inh = 100
N_exc = 300
N = N_inh + N_exc
# cell positions
positions = np.random.random((N,3))
# initialize the network
net = Network()
# add some populations
net.add_population(N_inh, type='inhibitory')
net.add_population(N_exc, type='excitatory')
# add the connectivity rule
net.connect(random_connectivity)
# build the matrix
cells, connections = net.build()
print len(connections)
# turn it into a sparse matrix
m = construct_matrix(connections)
# the connectivity to hdf5
Hdf5Util().write('connections.h5', m)
cells = pd.DataFrame.from_dict(cells)
cells['x'] = positions[:,0]
cells['y'] = positions[:,1]
示例5: TestSimple
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import connect [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()
示例6: Irc
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import connect [as 别名]
class Irc(Greenlet):
"""
irc connection abstraction. inherits:
start(), join(), kill(exception=GreenletExit, block=False, timeout=None), ready(), successful(), etc
__init__ only receives:
tag: "myfreenode",
fd: 2 or None
the other options are accessed through the following properties,
which delegate calls to conf.get:
servers: [Server("server.address +1234"), ...],
encoding: "utf-8"
network: "freenode",
nick: "sqrl",
username: "sqrl",
password: "server password",
nickservpassword: "nisckerv password",
realname: "real name",
chans: ["#channel": {"blacklist": ["ex"]}, ...],
scripts: ["users", "seen", "com", "version", "wik", "title", "choice", "dic", "ex", ...],
masters: ["*!*@unaffiliated/squirrel", ...]
"""
def __init__(self, tag, fd=None, me=None):
super(Irc, self).__init__()
self.tag = tag
self.net = Network(fd)
self.group = Group()
self.logger = logging.getLogger(self.tag)
self.logger.setLevel(1)
self.formatter = CuteFormatter(maxbytes=400, encoding=self.encoding)
self.connected = fd is not None
if self.connected:
self.me = me
else:
self.me = (self.nick, None, None)
def __repr__(self):
return u"Irc(tag=%s)" % self.tag
############################################################################################### core
def _run(self):
"""
greenlet starts here
connect to irc, serve in a loop
run self.disconnect() and self.onunload() on GreenletExit and die
"""
self.onload() # let it fail
try:
while True:
if not self.connected:
self.connect() # let it fail (should not happen, relly)
for chan in self.chans:
self.joinchan(chan)
while True:
try:
line = self.net.getline()
line = line.decode(self.encoding)
try:
msg = Message(irc=self, line=line)
except MessageMalformed as e:
self.onexception(e, unexpected=True)
continue
self.onmessage(msg)
if type(msg) == Message and msg.command == "ping":
self.send("PONG %s" % msg.params[0])
elif type(msg) == Numeric and msg.num == 1:
self.me = (msg.target, None, None)
self.onconnected(msg)
self.privmsg(msg.target, "id")
elif msg.frommyself:
self.me = msg.sender
self.formatter.maxbytes = 512 - 7 - len("".join(self.me).encode(self.encoding)) # :[email protected] <PRIVMSG :text>+\r\n"
self.logger.log(OTHER, "i am {0[0]}!{0[1]}@{0[2]} and i can send {1} bytes".format(self.me, self.formatter.maxbytes))
except ConnectionFailed as e:
self.onexception(e, unexpected=True)
self.disconnect()
break
except GreenletRehash: # don't disconnect
raise
except GreenletExit: # same as above, but disconnect
self.disconnect() # let it fail (should not happen, relly)
raise
except Exception as e:
self.onexception(e, unexpected=True)
finally:
self.onunload() # let it fail
def shutdown(self, exception=GreenletExit):
"""
kills sender greenlet, all greenlets in group, oneself
this will cause _run to exit and the thing should get deleted from memory
! if exception is GreenletExit, disconnects
"""
self.group.kill(exception, block=False)
self.kill(exception, block=False)
############################################################################################### my cute methods
#.........这里部分代码省略.........
示例7: __init__
# 需要导入模块: from network import Network [as 别名]
# 或者: from network.Network import connect [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
#.........这里部分代码省略.........