本文整理汇总了Python中connection.Connection.start方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.start方法的具体用法?Python Connection.start怎么用?Python Connection.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类connection.Connection
的用法示例。
在下文中一共展示了Connection.start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
def run(self):
logging.debug('Connecting to {}'.format(self.destination))
self._connect()
if not shared.shutting_down and self.success:
c = Connection(self.destination, 'i2p', self.s, 'i2p', False, self.destination)
c.start()
shared.connections.add(c)
示例2: run
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
def run(self):
log.info("btserver running")
while self.running:
self.server_sock = None
try:
self.server_sock = bt.BluetoothSocket(bt.RFCOMM)
self.server_sock.setblocking(0)
self.server_sock.bind(("", self.channel))
self.server_sock.listen(1)
bt.advertise_service(self.server_sock, config.PNAME,
service_classes = [bt.SERIAL_PORT_CLASS],
profiles = [bt.SERIAL_PORT_PROFILE])
log.info("Waiting for connections on RFCOMM channel [{}]".format(self.server_sock.getsockname()[1]))
while self.running:
readable, _, _ = select.select([self.server_sock], [], [], 0.1)
for s in readable:
if s is self.server_sock:
client_sock, client_info = self.server_sock.accept()
log.info("Accepted connection from: " + str(client_info))
client_sock.setblocking(1)
client_sock.settimeout(self.timeout)
if self.running:
conn = Connection(client_sock, self)
conn.start()
except:
if self.running:
log.exception("Error while listening for connections")
time.sleep(1.0)
finally:
self.close()
示例3: main
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [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(server_port):
print("Could not start connection on port {}".format(server_port))
return 1
connection.listen()
while 1:
if connection.is_connected():
print('server sending packet')
packet = [c for c in "server to client"]
connection.send_packet(packet)
while 1:
bytes_read, pack = connection.receive_packet(256)
if bytes_read == 0:
break
print("Received packet from client")
connection.update(delta_time)
time.sleep(delta_time)
示例4: run
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
def run(self):
while True:
if shared.shutting_down:
logging.debug('Shutting down Listener')
break
try:
conn, addr = self.s.accept()
logging.info('Incoming connection from: {}:{}'.format(addr[0], addr[1]))
with shared.connections_lock:
if len(shared.connections) > shared.connection_limit:
conn.close()
else:
c = Connection(addr[0], addr[1], conn, 'ip', True)
c.start()
shared.connections.add(c)
except socket.timeout:
pass
示例5: JammiNode
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [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
示例6: run
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
def run(self):
while not shared.shutting_down:
try:
destination = self._receive_line().split()[0]
logging.info('Incoming I2P connection from: {}'.format(destination.decode()))
hosts = set()
for c in shared.connections.copy():
hosts.add(c.host)
for d in shared.i2p_dialers.copy():
hosts.add(d.destination)
if destination in hosts:
logging.debug('Rejecting duplicate I2P connection.')
self.s.close()
else:
c = Connection(destination, 'i2p', self.s, 'i2p', True, destination)
c.start()
shared.connections.add(c)
self.new_socket()
except socket.timeout:
pass
logging.debug('Shutting down I2P Listener')
示例7: main
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [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)
示例8: CanopyClientNode
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [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
#.........这里部分代码省略.........
示例9: real
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
def real():
connection = Connection()
h = env.Handler(angle_main)
connection.configure_with(delegate=None, func=h)
connection.start()
示例10: Client
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
class Client(threading.Thread):
"""
The main class containing the wxPython graphical interface.
"""
def __init__(self):
print "client.py/Client.__init__"
threading.Thread.__init__(self)
self.isConnected = False
self.connection = None
self.tempCounter = 0
self.tempName = random.randint(1, 100)
def get_data(self):
# TODO Return the eye position
print "client.py/Client.get_data"
data = utilities.get_data()
if len(data):
return data
else:
return None
def connect(self):
# Connect to server
print "client.py/Client.connect"
# Start another thread for the connection
self.connection = Connection(netconstants.host, self.connected, self.display, self.lost_connection)
self.connection.start()
def disconnect(self):
# Disconnect from server
name = self.get_data() # TODO whut
self.connection.send_to_server(netconstants.CMD_QUIT + name)
def send(self):
# Send the data to server. Data is obtained by get_data().
print "client.py/Client.send"
if self.isConnected:
data = self.get_data()
print "client_send: ", data
if data is not None:
self.connection.send_to_server(data)
def set_name(self):
print "client.py/Client.set_name"
# Set an alternative name
if self.isConnected:
name = self.get_data() # TODO change this, name does not come from get_data()
if len(name):
self.connection.send_to_server(netconstants.CMD_RENAME + name)
def connected(self):
# This function is invoked in networking.Connection.run()
print "client.py/Client.connected"
self.isConnected = True
def display(self, data): # TODO DISPLAY EYE POSITION
print "client.py/Client.display"
# Display the eye positions
utilities.display(data)
def lost_connection(self, msg): # TODO
# This function is invoked in networking.Connection.run() when connection is lost
print "client.py/Client.lostConnection"
self.connection.join()
def quit(self):
# Quit connection
print "client.py/Client.quit"
if self.isConnected:
self.isConnected = False
self.connection.send_to_server(netconstants.CMD_QUIT + self.get_data()) # TODO ?
self.connection.join()
def run(self):
# TODO
import sys
old_stdout = sys.stdout
sys.stdout = open("clientout" + str(self.tempName) + ".txt", "w")
# - TODO -
self.connect()
#time.sleep(0.2)
while True:
self.send()
#time.sleep(0.05)
#time.sleep(0.2)
sys.stdout = old_stdout
示例11: RootDataRef
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
class RootDataRef(DataRef):
'''A reference to a root of a Firbase.'''
def __init__(self, url, ssl_options=None):
'''Construct a new Firebase reference from a full Firebase URL.'''
self.connection = Connection(url, self, ssl_options=ssl_options)
self.base_url = url
self.structure = Structure(self)
self.subscriptions = {}
self.history = []
self.connection.daemon = True
self.connection.start()
self._keep_alive()
atexit.register(self.close)
DataRef.__init__(self, self, '')
def _process(self, message):
'''Process a single incoming message'''
# This whole thing needs to be rewritten to use all the new information about the protocol
debug(message)
# If message type is data
if message['t'] == 'd':
data = message['d']
# If r is in data and set to 1 then it's probably a response
# to something we sent like a sub request or an auth token
if 'r' in data:
historical_entry = self.history[data['r']-1]
request = historical_entry['message']
callbacks = historical_entry['callbacks']
error = data['b']['s']
if error != 'ok':
if error == 'permission_denied':
path = request['d']['b']['p']
print 'FIREBASE WARNING: on() or once() for %s failed: %s' % (path, error)
elif error == 'expired_token' or error == 'invalid_token':
print 'FIREBASE WARNING: auth() failed: %s' % (error)
else:
path = request['d']['b']['p']
print 'FIREBASE WARNING: unknown for %s failed: %s' % (path, error)
onCancel = callbacks.get('onCancel', None)
if not onCancel is None:
onCancel(error)
onComplete = callbacks.get('onComplete', None)
if not onComplete is None:
onComplete(error if error != 'ok' else None)
# If t is in data then it's the response to the initial connection, maybe
elif 't' in data:
pass
# If a is in data, it's a new data blob for a node, maybe
elif 'a' in data:
if data['a'] == 'c':
# This type of message is created when we lose permission to read
# and it requires some extra effort to implement as we call onCancel
# for all effected callbacks, which are any anscestors of the path
pass
else:
b_data = data['b']
path = b_data['p']
path_data = b_data['d']
self._store(path, path_data)
# If message type is... control?
if message['t'] == 'c':
pass
def _store(self, path, path_data):
'''Store a single path worth of data into the strucutre.'''
if not path or path[0] != "/":
path = "/%s" % path
self.structure.store(path, path_data)
def _send(self, message, callbacks=None):
'''Send a single message to Firebase.'''
historical_entry = {
'message': message,
'callbacks': {} if callbacks is None else callbacks
}
self.history.append(historical_entry)
message['d']['r'] = len(self.history)
self.connection.send(message)
def _subscribe(self, path, query, callbacks=None):
'''Subscribe to updates regarding a path'''
isSubscribed = self._is_subscribed(path, query)
# A subscription (listen) request takes two main arguments, p (path) and q (query).
if not isSubscribed:
#.........这里部分代码省略.........
示例12: PusherAgent
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
class PusherAgent():
def __init__(self, host="ws.pusherapp.com", port=80, encryption=False, applicationKey=None, secret=None, userdata={}):
self.logger = logging.getLogger(__name__)
self.channels = {}
self.secret = secret
self.userdata = userdata
self.host = host
self.encryption = encryption
if self.encryption:
self.protocol = "wss"
# self.port = "443"
else:
self.protocol = "ws"
# self.port = "80"
self.port = port
self.applicationKey = applicationKey
self.client_id = 'js'
self.version = '1.7.1'
self.path = "app/%s?client=%s&version=%s" % (self.applicationKey,
self.client_id,
self.version)
self.url = "%s://%s:%s/%s" % (self.protocol,
self.host,
self.port,
self.path)
self.connection = Connection(self._connectionHandler, self.url)
self.connection.daemon = True
self.connection.start()
def disconnect(self):
self.connection.disconnect()
self.channels = {}
def subscribe(self, channelName):
data = {}
data['channel'] = channelName
self.logger.info('Subscribing to channel %s' % channelName)
if channelName.startswith('presence-'):
authKey = self._generatePresenceAuthKey(self.connection.socket_id,
self.applicationKey,
channelName,
self.secret,
self.userdata)
data['auth'] = authKey
data['channel_data'] = json.dumps(self.userdata)
elif channelName.startswith('private-'):
authKey = self._generatePrivateAuthKey(self.connection.socket_id,
self.applicationKey,
channelName,
self.secret)
data['auth'] = authKey
else:
authKey = ""
self.connection._send_event('pusher:subscribe', data)
self.channels[channelName] = Channel(channelName)
self.logger.info('Subscribed to %s' % channelName)
return self.channels[channelName]
def unsubscribe(self, channelName):
if channelName in self.channels.keys():
self.connection._send_event('pusher:unsubscribe',
{'channel':channelName,
}
)
del self.channels[channelName]
def channel(self, channelName):
channel = None
if channelName in self.channels.keys():
channel = self.channels[channelName]
return channel
def _connectionHandler(self, eventName, data, channelName):
if channelName in self.channels.keys():
self.logger.debug('PusherAgent distributing message to %s' % channelName)
self.channels[channelName]._handle_event(eventName, data)
def _generatePrivateAuthKey(self, socket_id,
applicationKey,
channelName,
secret):
authKey = ""
if socket_id and applicationKey and channelName and secret:
#.........这里部分代码省略.........
示例13: Pusher
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
class Pusher(object):
host = "ws.pusherapp.com"
client_id = 'PythonPusherClient'
protocol = 6
def __init__(self, key, secure=True, secret=None, user_data=None):
self.key = key
self.secret = secret
self.user_data = user_data or {}
self.channels = {}
self.connection = Connection(self._connection_handler, self._build_url(key, secure))
def connect(self):
"""Connect to Pusher"""
self.connection.start()
def disconnect(self):
"""Disconnect from Pusher"""
self.connection.disconnect()
self.channels = {}
def subscribe(self, channel_name):
"""Subscribe to a channel
:param channel_name: The name of the channel to subscribe to.
:type channel_name: str
:rtype : Channel
"""
data = {'channel': channel_name}
if channel_name.startswith('presence-'):
data['auth'] = self._generate_presence_key(
self.connection.socket_id,
self.key,
channel_name,
self.secret,
self.user_data
)
data['channel_data'] = json.dumps(self.user_data)
elif channel_name.startswith('private-'):
data['auth'] = self._generate_private_key(
self.connection.socket_id,
self.key,
channel_name,
self.secret
)
self.connection.send_event('pusher:subscribe', data)
self.channels[channel_name] = Channel(channel_name, self.connection)
return self.channels[channel_name]
def unsubscribe(self, channel_name):
"""Unsubscribe from a channel
:param channel_name: The name of the channel to unsubscribe from.
:type channel_name: str
"""
if channel_name in self.channels:
self.connection.send_event(
'pusher:unsubscribe', {
'channel': channel_name,
}
)
del self.channels[channel_name]
def channel(self, channel_name):
"""Get an existing channel object by name
:param channel_name: The name of the channel you want to retrieve
:type channel_name: str
:rtype: Channel or None
"""
return self.channels.get(channel_name)
def _connection_handler(self, event_name, data, channel_name):
if channel_name in self.channels:
self.channels[channel_name]._handle_event(event_name, data)
@staticmethod
def _generate_private_key(socket_id, key, channel_name, secret):
auth_key = ""
if socket_id and key and channel_name and secret:
subject = "%s:%s" % (socket_id, channel_name)
h = hmac.new(secret, subject, hashlib.sha256)
auth_key = "%s:%s" % (key, h.hexdigest())
return auth_key
@staticmethod
def _generate_presence_key(socket_id, key, channel_name, secret, user_data):
auth_key = ""
if socket_id and key and channel_name and secret and user_data:
#.........这里部分代码省略.........
示例14: RootDataRef
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
class RootDataRef(DataRef):
"""A reference to a root of a Firbase."""
def __init__(self, url):
"""Construct a new Firebase reference from a full Firebase URL."""
self.connection = Connection(url, self)
self.base_url = url
self.structure = Structure(self)
self.subscriptions = {}
self.history = []
self.connection.daemon = True
self.connection.start()
atexit.register(self.close)
DataRef.__init__(self, self, "")
def _process(self, message):
"""Process a single incoming message"""
# This whole thing needs to be rewritten to use all the new information about the protocol
debug(message)
# If message type is data
if message["t"] == "d":
data = message["d"]
# If r is in data and set to 1 then it's probably a response
# to something we sent like a sub request or an auth token
if "r" in data:
historical_entry = self.history[data["r"] - 1]
request = historical_entry["message"]
callbacks = historical_entry["callbacks"]
error = data["b"]["s"]
if error != "ok":
if error == "permission_denied":
path = request["d"]["b"]["p"]
print "FIREBASE WARNING: on() or once() for %s failed: %s" % (path, error)
elif error == "expired_token" or error == "invalid_token":
print "FIREBASE WARNING: auth() failed: %s" % (error)
else:
path = request["d"]["b"]["p"]
print "FIREBASE WARNING: unknown for %s failed: %s" % (path, error)
onCancel = callbacks.get("onCancel", None)
if not onCancel is None:
onCancel(error)
onComplete = callbacks.get("onComplete", None)
if not onComplete is None:
onComplete(error if error != "ok" else None)
# If t is in data then it's the response to the initial connection, maybe
elif "t" in data:
pass
# If a is in data, it's a new data blob for a node, maybe
elif "a" in data:
if data["a"] == "c":
# This type of message is created when we lose permission to read
# and it requires some extra effort to implement as we call onCancel
# for all effected callbacks, which are any anscestors of the path
pass
else:
b_data = data["b"]
path = b_data["p"]
path_data = b_data["d"]
self._store(path, path_data)
# If message type is... control?
if message["t"] == "c":
pass
def _store(self, path, path_data):
"""Store a single path worth of data into the strucutre."""
if not path or path[0] != "/":
path = "/%s" % path
self.structure.store(path, path_data)
def _send(self, message, callbacks=None):
"""Send a single message to Firebase."""
historical_entry = {"message": message, "callbacks": {} if callbacks is None else callbacks}
self.history.append(historical_entry)
message["d"]["r"] = len(self.history)
self.connection.send(message)
def _subscribe(self, path, query, callbacks=None):
"""Subscribe to updates regarding a path"""
isSubscribed = self._is_subscribed(path, query)
# A subscription (listen) request takes two main arguments, p (path) and q (query).
if not isSubscribed:
message = {"t": "d", "d": {"r": 0, "a": "l", "b": {"p": path}}}
if not query is None:
message["d"]["b"]["q"] = query
#.........这里部分代码省略.........
示例15: Connection
# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import start [as 别名]
from connection import Connection
from testconfig import TestConfig
host = TestConfig.host
port = TestConfig.port
conn = Connection(host, port, "test8888", "test", "test", "test")
conn.send("NICK " + TestConfig.nickname)
conn.send("USER " + TestConfig.username + " " + TestConfig.hostname + " " + TestConfig.servername + " :" + TestConfig. realname)
conn.start()
print "Execution terminated."