本文整理汇总了Python中connection.Connection.send_message方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.send_message方法的具体用法?Python Connection.send_message怎么用?Python Connection.send_message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类connection.Connection
的用法示例。
在下文中一共展示了Connection.send_message方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: JammiNode
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send_message [as 别名]
class JammiNode(object):
def __init__(self, host, port, name, broadcasting):
self.host = host
self.port = port
self.name = name
self.conn = Connection(host, port, name)
self.conn.start()
self.subs = dict()
self.broadcasting = broadcasting
self.pub_man = pm.PublisherManager()
def run(self):
for topic, msg_type, trusted in self.broadcasting:
self.create_subscriber(topic, msg_type, trusted)
while not rospy.is_shutdown():
updates = self.conn.updates()
for v in updates.values():
self.pub_man.publish(v)
self.conn.stop()
def create_subscriber(self, topic, msg_type, trusted):
namespace, msg_name = msg_type.split("/")
mod = __import__(namespace + ".msg")
msg_cls = getattr(mod.msg, msg_name)
cb = self.create_callback(topic, msg_type, trusted)
self.subs[topic] = rospy.Subscriber(topic, msg_cls, cb, None, 1)
return self
def create_callback(self, topic, msg_type, trusted):
def callback(msg):
data = dict()
data["to"] = trusted.split(' ')
data["from"] = self.name
data["topic"] = "/{}{}".format(self.name, topic)
data["type"] = msg_type
data["stamp"] = time.time()
data["msg"] = mc.convert_ros_message_to_dictionary(msg)
self.conn.send_message(data)
return callback
示例2: CanopyClientNode
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send_message [as 别名]
class CanopyClientNode(object):
def __init__(self, host, port, name, broadcasting, private_key,
description, global_frames):
self.host = host
self.port = port
self.name = name.replace(" ", "").replace("/", "")
self.conn = dict()
self.receiver = None
self.descriptionConn = None
self.subs = dict()
self.broadcasting = broadcasting
self.private_key = private_key
self.description = description
self.global_frames = global_frames
self.pub_man = pm.PublisherManager()
self.timer = threading.Timer(0.1, self.descriptionSend)
# Creates all connections and subscribers and starts them.
# Runs a loop that checks for received messages.
def run(self):
for topic, msg_type, trusted in self.broadcasting:
if topic[0] != "/":
topic = "/" + topic
self.create_subscriber(topic, msg_type, trusted)
if topic == "/receiving":
rospy.logerr("{}: topic name 'receiving' is reserved".format(
self.name))
continue
self.conn[topic] = Connection(host, port, "{}{}".format(
self.name, topic), private_key)
self.conn[topic].start()
self.receiver = Connection(host, port, "{}{}".format(
self.name, "/receiving"), private_key)
self.descriptionConn = Connection(host, port, "{}/description".format(
self.name), private_key)
self.receiver.start()
self.descriptionConn.start()
self.timer.start()
while not rospy.is_shutdown():
#for key, conn in self.conn.iteritems():
# updates = conn.updates()
updates = self.receiver.updates()
for v in updates.values():
self.pub_man.publish(v)
for key, conn in self.conn.iteritems():
conn.stop()
self.receiver.stop()
self.timer.cancel()
self.descriptionConn.stop()
# Creates a subscriber for messages of msg_type published on topic.
def create_subscriber(self, topic, msg_type, trusted):
namespace, msg_name = msg_type.split("/")
mod = __import__(namespace + ".msg")
msg_cls = getattr(mod.msg, msg_name)
cb = self.create_callback(topic, msg_type, trusted)
self.subs[topic] = rospy.Subscriber(topic, msg_cls, cb, None, 1)
return self
# Creates a callback function for the subscribers.
# Formats the packet as a dictionary and sends it to the Connection.
def create_callback(self, topic, msg_type, trusted):
def callback(msg):
if msg._connection_header["callerid"] == rospy.get_name():
return
data = dict()
data["To"] = trusted.split(' ')
data["From"] = self.name
if topic == "/tf":
data["Topic"] = topic
else:
data["Topic"] = "/{}{}".format(self.name, topic)
data["Type"] = msg_type
data["Stamp"] = time.time()
data["Private_key"] = self.private_key
if msg_type == "tf2_msgs/TFMessage":
for t in msg.transforms:
t = self.modify_stamped_message(t)
else:
msg = self.modify_stamped_message(msg)
data["Msg"] = mc.convert_ros_message_to_dictionary(msg)
self.conn[topic].send_message(data)
return callback
def modify_stamped_message(self, message):
if hasattr(message, 'child_frame_id'):
if (message.child_frame_id.find("/") > 0 or
message.child_frame_id.count("/") > 1):
return message
if message.child_frame_id not in self.global_frames:
if message.child_frame_id[0] != "/":
message.child_frame_id = "/" + message.child_frame_id
message.child_frame_id = "{}{}".format(self.name,
message.child_frame_id)
if hasattr(message, 'header'):
if ((not hasattr(message, 'child_frame_id')) and
message.header.frame_id.find("/") > 0 and
message.header.frame_id.count("/") > 1):
return message
#.........这里部分代码省略.........
示例3: __init__
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send_message [as 别名]
class Game:
def __init__(self, **kwargs):
self.index = kwargs.get('index')
self.game_id = kwargs.get('game_id')
self.nickname = kwargs.get('nickname', None)
self.prefix = kwargs.get('prefix', None)
def start(self):
self.connection = Connection(self.index, self)
self.connection.start_game()
def game_completed(self, results):
logging.info(
'Bot %d; Game completed. Nickname: %s. Ranked #%d of %d. %d of %d correct answers' % (
self.index, self.nickname, results['rank'], results['playerCount'],
results['correctCount'], len(results['answers'])
)
)
self.connection.stop_ping()
def get_next_question(self):
while True:
result = self.connection.receive_message('/service/player')
if 'data' in result:
data = result['data']
else:
continue
if 'id' in data:
awaiting_question = data['id'] == 1
else:
continue
if 'content' in data:
content = json.loads(data['content'])
else:
continue
if 'playerCount' in content:
self.game_completed(content)
return None
if ('quizQuestionAnswers' not in content or 'questionIndex' not in content or
'answerMap' not in content):
continue
quiz_question_answers = content['quizQuestionAnswers']
question_index = content['questionIndex']
answers = content['answerMap']
if question_index >= len(quiz_question_answers) or question_index < 0:
logging.error(
'Bot %d; Invalid question index; %s' % (self.index, str(question_index))
)
return question_index >= len(quiz_question_answers)
number_of_answers = quiz_question_answers[question_index]
return Question(awaiting_question, question_index, number_of_answers, answers)
def answer_question(self, answer_index):
self.connection.send_message('/service/controller', {
'data': {
'id': 6,
'type': 'message',
'gameid': self.game_id,
'host': 'kahoot.it',
'content': json.dumps({
'choice': answer_index,
'meta': {
'lag': 22,
'device': {
'userAgent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:48.0) ' +
'Gecko/20100101 Firefox/48.0',
'screen': {
'width': 1920,
'height': 1080,
}
}
}
})
}
})
result = self.connection.receive_message('/service/controller')
if not result['successful']:
logging.error('Bot %d; Was not able to answer question' % self.index)
示例4: Bot
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send_message [as 别名]
class Bot(object):
def __init__(self, version = "HansBot"):
self.version = version
self.state = BotState(self)
self.connection = None
def start(self, server, nickname):
if self.connection:
LOGGER.warning("Starting the bot twice. Will disconnect old bot.")
self.stop()
self.connection = Connection(server, nickname, delegate = self.state,
version = self.version)
def join(self):
self.connection.join()
def send_message(self, user, message):
self.connection.send_message(destination = user.session, message = message)
def stop(self):
self.connection.stop()
self.connection = None
def rejected(self):
self.stop()
def connected(self):
pass
def channels(self):
return self.state.channels_by_id.values()
def users(self):
return self.state.users_by_session.values()
def get_channel_by_id(self, id):
return self.state.channels_by_id[id]
def get_user_by_id(self, id):
return self.state.users_by_id[id]
def get_user_by_name(self, name):
for u in self.state.users_by_session:
if self.state.users_by_session[u].name == name:
return self.state.users_by_session[u]
return None
def get_root(self):
return self.state.root
def is_connected(self):
return self.connection is not None
##############################################################################
### EVENTS FROM STATE
def on_text_message(self, from_user, to_users, to_channels, tree_ids,
message):
if self.state.user.session in to_users:
self.on_message_self(from_user = from_user, message = message)
if to_users:
self.on_message_users(from_user = from_user, to_users = to_users,
message = message)
if to_channels:
self.on_message_channels(from_user = from_user, to_channels = to_channels,
message = message)
if tree_ids:
self.on_message_trees(from_user = from_user, tree_ids = tree_ids,
message = message)
def on_voice_ping(self, session_id):
pass
def on_voice_talk(self, from_user, sequence, data):
pass
##############################################################################
### EVENTS
def on_message_self(self, from_user, message):
pass
def on_message_users(self, from_user, to_users, message):
pass
def on_message_channels(self, from_user, to_channels, message):
pass
def on_message_trees(self, from_user, tree_ids, message):
pass
示例5: ConnectionPool
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send_message [as 别名]
class ConnectionPool(object):
"""Connection Pool to a single mongo instance.
:Parameters:
- `mincached` (optional): minimum connections to open on instantiation. 0 to open connections on first use
- `maxcached` (optional): maximum inactive cached connections for this pool. 0 for unlimited
- `maxconnections` (optional): maximum open connections for this pool. 0 for unlimited
- `maxusage` (optional): number of requests allowed on a connection before it is closed. 0 for unlimited
- `dbname`: mongo database name
- `**kwargs`: passed to `connection.Connection`
"""
def __init__(self,
mincached=0,
maxcached=0,
maxconnections=0,
maxusage=0,
dbname=None,
dbuser=None,
dbpass=None,
*args, **kwargs):
assert isinstance(mincached, int)
assert isinstance(maxcached, int)
assert isinstance(maxconnections, int)
assert isinstance(maxusage, int)
assert isinstance(dbname, (str, unicode, None.__class__))
if mincached and maxcached:
assert mincached <= maxcached
if maxconnections:
assert maxconnections >= maxcached
assert maxconnections >= mincached
self._args, self._kwargs = args, kwargs
self._maxusage = maxusage
self._mincached = mincached
self._maxcached = maxcached
self._maxconnections = maxconnections
self._idle_cache = [] # the actual connections that can be used
self._condition = Condition()
self._dbname = dbname
self._dbuser = dbuser
self._dbpass = dbpass
self._connections = 0
# Establish an initial number of idle database connections:
idle = [self.connection() for i in range(mincached)]
while idle:
self.cache(idle.pop())
def new_connection(self):
kwargs = self._kwargs
kwargs['pool'] = self
self.conn = Connection(*self._args, **kwargs)
# Authenticate if user and pass are set
if self._dbuser and self._dbpass:
c = copy.copy(self)
try:
self.conn.send_message(
message.query(0,
"%s.$cmd" % self._dbname,
0,
1,
SON({'getnonce' : 1}),
SON({})
), callback=c._on_get_nonce)
except Exception as e:
# logging.error(str(e))
raise
return c.conn
else:
return self.conn
def connection(self):
""" get a cached connection from the pool """
self._condition.acquire()
try:
if (self._maxconnections and self._connections >= self._maxconnections):
raise TooManyConnections("%d connections are active greater than max: %d" % (self._connections, self._maxconnections))
# connection limit not reached, get a dedicated connection
try: # first try to get it from the idle cache
con = self._idle_cache.pop(0)
except IndexError: # else get a fresh connection
con = self.new_connection()
self._connections += 1
finally:
self._condition.release()
return con
def cache(self, con):
"""Put a dedicated connection back into the idle cache."""
if self._maxusage and con.usage_count > self._maxusage:
self._connections -=1
# logging.info('dropping connection %s uses past max usage %s' % (con.usage_count, self._maxusage))
con._close()
return
self._condition.acquire()
#.........这里部分代码省略.........
示例6: GameManager
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import send_message [as 别名]
#.........这里部分代码省略.........
text_ip = self.find_widget('text_ip')
text_port = self.find_widget('text_port')
text_name = self.find_widget('text_name')
ip_address = text_ip.document.text
port_num = int(text_port.document.text)
name = text_name.document.text
else:
#debug mode
text_ip = "127.0.0.1"
#text_ip = "192.168.254.103"
text_port = "8080"
text_name = "DebugX"
ip_address = text_ip
port_num = int(text_port)
name = text_name
#attributes
player_class = choice(Resources.types)
player_x,player_y = randint(5+34,Resources.window_width-(5+34)),randint(5+34,Resources.window_height-(5+34))
player_actual_name = name
#connect to server
self.my_connection.join_server((ip_address,port_num))
self.me.set_data(player_class,player_actual_name,"temp")
self.me.x,self.me.y = player_x,player_y
#register player to server
print "me:",self.me.get()
print "Sending player..."
if self.my_connection.send_message(self.me.get()) is None:
self.me.name = self.my_connection.receive_message()
print "Complete!"
else:
print "Error!"
#socket details
print "IP Address:",ip_address
print "Port:",port_num
print "Name:",name
def set_info_bar(self):
info_bar = self.find_widget('info_bar')
info_bar.opacity = 185
thumbnail = self.find_widget('thumbnail')
thumbnail.image = Resources.sprites['thumb_'+self.me.type]
player_name = self.find_label('player_name')
player_name.text = self.me.actual_name
#Utilities
def set_client(self,player):
self.me = player
def set_window(self,window):
self.window = window
def set_media(self,media):
self.media = media
self.media.volume = 0.75
self.media.eos_action = self.media.EOS_LOOP
self.media.play()
def set_focus(self,focus):