本文整理汇总了Python中connection.Connection.connect方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.connect方法的具体用法?Python Connection.connect怎么用?Python Connection.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类connection.Connection
的用法示例。
在下文中一共展示了Connection.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_near
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def send_near(output_lock, neighbors, msg):
for peer in neighbors:
# Non invio all'indirizzo da cui è arrivato il pacchetto
# if sender is None or (peer['ipv4'] != sender and peer['ipv6'] != sender):
try:
output(output_lock, "\nConnecting to: " + peer['ipv4'] + "\t" + peer['ipv6'] + "\t" + peer['port'])
c = Connection(output_lock, peer['ipv4'], peer['ipv6'],
peer['port']) # Creazione connessione con un peer noto
c.connect()
peerSock = c.socket
peerSock.send(msg)
output(output_lock, "\nMessage sent : ")
output(output_lock,
msg[0:4] + "\t" + msg[4:20] + "\t" + msg[20:35] + "\t" + msg[36:75] + "\t" + msg[76:80] + "\t" + msg[
80:112])
peerSock.close()
except IOError as e:
output(output_lock, 'send_near-Socket Error: ' + e.message)
except socket.error, msg:
output(output_lock, 'send_near-Socket Error: ' + str(msg))
continue
except Exception as e:
output(output_lock, 'send_near-Error: ' + e.message)
continue
示例2: main
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def main():
protocol_path = os.path.normpath(os.path.expanduser(Config.MC_DATA_FOLDER))
threaded_dispatcher = ThreadedDispatcher()
connection = Connection(Config.SERVER, Config.PORT)
factory = PacketFactory(protocol_path, Config.PROTOCOL_VERSION)
agent_reactor = ModelReactor(factory, connection)
inventory = InventoryReactor(factory, connection)
packet_reactor = PacketReactor(factory, connection)
# TODO should the inventory reactor be on the model?
robot = Robot(factory, model=agent_reactor, inventory=inventory)
#
# establish our threaded dispatcher
# TODO need a better way to do this
#
#
# TODO need a way to signal threaded reactors to shutdown gracefully
#
connection.raw_packet_emitter.dispatcher = threaded_dispatcher
packet_reactor.play_state_emitter.dispatcher = threaded_dispatcher
packet_reactor.state_change_emitter.dispatcher = threaded_dispatcher
packet_reactor.login_state_emitter.dispatcher = threaded_dispatcher
packet_reactor.handshake_state_emitter.dispatcher = threaded_dispatcher
agent_reactor.stop_emitter.dispatcher = threaded_dispatcher
agent_reactor.tick_emitter.dispatcher = threaded_dispatcher
# connection
connection.raw_packet_emitter.bind(packet_reactor)
# packet_reactor
packet_reactor.play_state_emitter.bind(agent_reactor)
packet_reactor.play_state_emitter.bind(inventory)
packet_reactor.play_state_emitter.bind(robot)
# agent_reactor
agent_reactor.stop_emitter.bind(robot)
agent_reactor.tick_emitter.bind(robot)
try:
connection.connect()
packet_reactor.login('bobo')
while True:
connection.process()
finally:
agent_reactor.stop()
threaded_dispatcher.stop()
raise
示例3: main
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def main(reactor, passes, ip):
connection = Connection('testUser', 'testRobot', reactor)
benchmark = Benchmark(passes, connection, reactor)
print('Connect...')
deferred = Deferred()
deferred.addCallback(benchmark.run)
connection.connect('ws://{0}:9000/'.format(ip), deferred)
reactor.run()
示例4: main
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def main(reactor, passes, ip):
user = 'testUser'
robot = 'testRobot'
connection = Connection(user, robot, user, reactor)
benchmark = Benchmark(passes, connection, robot, reactor)
print('Connect...')
deferred = Deferred()
deferred.addCallback(benchmark.run)
connection.connect('http://{0}:9000/'.format(ip), deferred)
reactor.run()
示例5: Client
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
class Client(Listener):
def __init__(self):
Listener.__init__(self)
self.parser = Parser()
self.connection = Connection()
self.connection.add_listener("readline", self.readline_handler)
self.connection.add_listener("connect", self.connect_handler)
self.connection.add_listener("disconnect", self.disconnect_handler)
self.connection.connect()
def connect_handler(self, event):
self.add_listener("ping", self.ping_handler)
event.connection.send("NICK foo")
event.connection.send("USER foo 0 * :foo")
self.add_listener("welcome", self.ready_handler)
self.add_listener("privmsg", self.message_handler)
# TODO
# Make it as AutoJoinPlugin
def join(self, channel):
self.connection.send("JOIN " + channel)
def message_handler(self, event):
print "--" + event.message + "--"
if event.message == "quit":
self.connection.send("QUIT")
self.connection.send("PRIVMSG " + event.channel + " :" + event.message)
def ready_handler(self, event):
self.join("#foo")
# TODO
# Make it as PingPlugin
def ping_handler(self, event):
event.connection.send("PONG " + event.data)
def disconnect_handler(self, event):
print self
def readline_handler(self, event):
e = self.parser.parse(event)
#print event.data
if e:
self.dispatch(e)
示例6: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
class Bot:
def __init__(self, ed):
self.ed = ed
def start(self):
self._connections = [
self.ed.add(ConnectedEvent, Wbm(self.start_modules)),
self.ed.add(ReloadconfigEvent, Wbm(self.reload_config)),
self.ed.add(ConnectionClosedEvent, Wbm(self.connection_closed))
]
self.read_config()
self.console = ConsoleView(self.ed)
self.server = Connection(self.ip, self.port, self.ed)
self.server.connect(self.ssl)
def start_modules(self, event):
self.modules = moduleloader.load_modules(self.ed)
LoginEvent(self.name).post(self.ed)
def reload_config(self, event):
if event.module == "core" or event.module == "all":
self.read_config()
if event.module == "modules":
self.modules = []
reload(moduleloader)
self.modules = moduleloader.reload_modules(self.modules, self.ed)
def connection_closed(self, event):
if (event.type == "server" and self.reconnect) or event.type == "reconnect":
self.restart()
else:
QuitEvent().post(self.ed)
def restart(self):
self._connections = None
self.config = None
self.modules = None
self.server = None
self.start()
def read_config(self):
config = bot_info["Connection"]#read_config_section(os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.cfg"), "Connection")
self.ip = config["prefix"][1] + config["ip"]#random.choice(config["prefix"]) + config["ip"]
self.port = config["port"][2]#random.choice(config["port"])
self.name = bot_info["General"]["name"]
self.ssl = config["ssl"]
self.reconnect = config["reconnect"]
示例7: main
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def main():
conn = Connection()
conn.connect()
bot = Bot(conn)
while True:
bot.update_loop()
raw_log = conn.log()
if raw_log:
logs = raw_log.split('\r\n')
for log in logs:
bot.eat_log(log)
示例8: question
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def question(self):
html = Connection.connect(self.url + '/top-answers')
soup = BeautifulSoup(html, 'html.parser')
questions = []
for ask in soup.find_all('a', 'question_link'):
# q_str = str(ask.get_text().encode('utf8'))
q_href = str(addr + str(ask.get('href')))
yield Question(q_href)
示例9: topic
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def topic(self):
html = Connection.connect(addr + '/people/' + self.account + '/topics')
soup = BeautifulSoup(html, "html.parser")
topics = []
for topic in soup.find_all('a', 'zm-list-avatar-link'):
# topic_str = str(topic.strong.get_text())
topic_href = addr + str(topic.get('href'))
topics.append(Topic(topic_href))
return topics
示例10: ask
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def ask(self):
html = Connection.connect(addr + '/people/' + self.account + '/asks')
soup = BeautifulSoup(html, "html.parser")
questions = dict()
for ask in soup.find_all('a', 'question_link'):
q_str = str(ask.get_text().encode('utf8'))
q_href = str(addr + str(ask.get('href')))
questions[q_str] = q_href
return questions
示例11: send_aque
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def send_aque(output_lock, ipv4, ipv6, port, msg):
try:
output(output_lock, "\nConnecting to: " + ipv4 + "\t" + ipv6 + "\t" + port)
c = Connection(output_lock, ipv4, ipv6, port) # Creazione connessione con un peer noto
c.connect()
peerSock = c.socket
peerSock.send(msg)
output(output_lock, "\nMessage sent: ")
output(output_lock,
msg[0:4] + "\t" + msg[4:20] + "\t" + msg[20:35] + "\t" + msg[36:75] + "\t" + msg[76:80] + "\t" + msg[80:112])
peerSock.close()
except IOError as e:
if e.errno == errno.EPIPE:
pass
except socket.error, msg:
output(output_lock, 'send_aque-Socket Error: ' + str(msg))
示例12: main
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
def main():
server_port = 30000
client_port = 30001
protocol_id = 0x99887766
delta_time = 0.25
send_rate = 0.25
time_out = 10
connection = Connection(protocol_id, time_out)
if not connection.start(client_port):
print("Could not start connection on port {}".format(client_port))
return
connection.connect(Address(a=127,b=0,c=0,d=1,port=server_port))
connected = False
while 1:
if not connected and connection.is_connected():
print("Client connected to server")
connected = True
if not connected and connection.connect_failed():
print("Connection failed")
break
packet = [c for c in 'client to server']
sent_bytes = connection.send_packet(packet)
while 1:
bytes_read, pack = connection.receive_packet(256)
if bytes_read == 0:
break
print("Received packet from server")
connection.update(delta_time)
time.sleep(delta_time)
示例13: Source
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
class Source(object):
def __init__(self, **kwargs):
self._socket = None
self._conf = kwargs
self._conn = None
self._tables = {}
def _query(self, sql):
"""
Query mysql with reconnecting once on failure.
"""
try:
res = []
with open_cursor(self._conn) as cursor:
cursor.execute(sql)
columns_desc = cursor.description
columns = tuple([d[0] for d in columns_desc])
for row in cursor:
res.append(dict(zip(columns, row)))
return res, columns_desc
except:
self.disconnect()
self.connect()
res = []
with open_cursor(self._conn) as cursor:
cursor.execute(sql)
columns_desc = cursor.description
columns = tuple([d[0] for d in columns_desc])
print cursor.description
for row in cursor:
res.append(dict(zip(columns, row)))
return res, columns_desc
def connect(self):
"""
build connection to mysql server.
"""
self._conn = Connection(**(self._conf))
self._conn.connect()
self._socket = self._conn.socket
def disconnect(self):
"""
disconnect mysql server.
"""
self._conn.close()
self._socket = None
def show_master_status(self):
res, _ = self._query("show master status;")
print res
return res[0]
def get_server_id(self):
return 123456
def binlog_dump(self, log_file, offset):
"""
COM_BINLOG_DUMP
+=============================================+
| packet header | packet length 0 : 3 |
| +-------------------------+
| | sequence number 3 : 1 |
+============================================+
| command packet | command code 4 : 1 | COM_BINLOG_DUMP
| +------------------------―+
| | offset 5 : 4 |
| +-------------------------+
| | flags 9 : 2 |
| +-------------------------+
| | server id 11 : 4|
| +-------------------------+
| | log name 15 : x|
+============================================+
"""
payload = ""
payload += utils.int1store(ServerCmd.BINLOG_DUMP)
payload += utils.int4store(offset)
payload += utils.int2store(0)
payload += utils.int4store(self.get_server_id())
payload += log_file
payload += "\x00"
log.debug("len(payload) = %d" % len(payload))
# send BIGLOGDUMP command and parse ok packet response.
self._socket.send(payload, 0)
ok_packet = self._socket.recv()
parser = MySQLProtocol()
ok_packet = parser.parse_ok(ok_packet)
print ok_packet
def __iter__(self):
return self
def next(self):
packet = self._socket.recv()
event = BinlogEvent(packet)
log.debug(str(event))
if event.is_eof() or event.is_error():
#.........这里部分代码省略.........
示例14: XPush
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
class XPush(object):
hostname = ""
appId = ""
userEventNames = {}
_channels = {}
Context = None
_sessionConnection = None
def __init__(self, host, appId, eventHandler=None, autoInitFlag=True):
if host is None:
return 'params(1) must have hostname'
if appId is None:
return 'params(2) must have appId'
self.hostname = host #applicationKey
self.appId = appId #applicationKey
self.userId = "someone"
self.deviceId = "WEB"
self.token = ""
self.info = None
self.Context = {
"SIGNUP" : '/user/register',
"LOGIN" : '/auth',
"Channel" : '/channel',
"Signout" : '/signout',
"Message" : '/msg',
"NODE" : '/node'
}
def createSimpleChannel(self, channel, userObj, callback):
data = self._getChannelInfo(channel)
ch = self._makeChannel(channel, data, True)
ch.connect( callback )
def _makeChannel(self, channel, server, channelOnly=False):
ch = Connection(self, TYPE_CHANNEL, server, channel, channelOnly)
if channel :
ch.channel = channel
self._channels[channel] = ch
return ch
def _getChannelInfo(self, channel):
response = self.rest( self.Context.get('NODE')+'/'+self.appId+'/'+channel , 'GET', {}, {} )
res = json.loads( response )
return res.get( "result" ).get( "server" )
def rest(self, context, method, data, headers ):
if method == 'GET' :
url = self.hostname+context
response = request.get( url )
return response.text
else :
url = self.hostname+context
response = request.post(
url=url,
data=data,
headers=headers
)
return response.text
def getChannelAsync(self, channel):
ch = self.getChannel(channel);
if ch is None :
self._channels[channel] = ch
serverInfo = self._getChannelInfo(channel)
ch = self._makeChannel(channel, serverInfo)
if( serverInfo ) :
ch.setServerInfo(serverInfo)
return ch
def getChannel(self, channel ):
return self._channels.get( channel )
def on_response(*args):
print('on_response', args)
def send(self, channel, name, data ):
ch = self.getChannelAsync(channel)
ch.send(name,data,self.on_response)
def joinChannel(self,channel,param,cb):
ch = self.getChannelAsync(channel)
ch.joinChannel( param, cb )
def login(self,userId, password, deviceId, cb):
self.userId = userId
if deviceId is None :
deviceId = 'WEB'
self.deviceId = deviceId
sendData = {"A": self.appId, "U": userId, "PW": password, "D": deviceId}
response = self.rest( self.Context.get('LOGIN'), 'POST', sendData, {} )
#.........这里部分代码省略.........
示例15: Client
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import connect [as 别名]
#.........这里部分代码省略.........
)
added = listener.add_callback(ev_type, cid, obj)
if not added:
failed = obj
listener.remove_callbacks(cid, last=icb)
break
icb += 1
self.log.debug("'{}' event callback '{}' added for id '{}'"
.format(ev_type, obj.__name__, cid))
if failed:
raise TypeError("app load failed since '{}' is not a valid"
"callback type".format(failed))
# register locally
self._apps[name] = app
app.cid, app.name = cid, name
return app.cid
def unload_app(self, ns):
"""Unload all callbacks associated with a particular app
namespace object
"""
name = utils.get_name(ns)
app = self._apps.pop(name)
finalize = getattr(app, '_finalize', False)
if finalize:
try:
next(finalize)
except StopIteration:
pass
return self.listener.remove_callbacks(app.cid)
def disconnect(self):
"""Disconnect the client's underlying connection
"""
self._con.disconnect()
time.sleep(0.1)
def connect(self):
"""Connect this client
"""
self._con.connect()
assert self.connected(), "Failed to connect to '{}'".format(
self.server)
def connected(self):
"""Check if connection is active
"""
return self._con.connected()
def api(self, cmd, exc=True):
'''Invoke esl api command with error checking
Returns an ESL.ESLEvent instance for event type "SOCKET_DATA"
'''
# note api calls do not require an active listener
# since we can handle the event processing synchronously
event = self._con.api(cmd)
try:
consumed, response = EventListener._handle_socket_data(event)
except CommandError:
if exc:
raise
return event
def cmd(self, cmd):