当前位置: 首页>>代码示例>>Python>>正文


Python Connection.disconnect方法代码示例

本文整理汇总了Python中connection.Connection.disconnect方法的典型用法代码示例。如果您正苦于以下问题:Python Connection.disconnect方法的具体用法?Python Connection.disconnect怎么用?Python Connection.disconnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在connection.Connection的用法示例。


在下文中一共展示了Connection.disconnect方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_nzb_content

# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import disconnect [as 别名]
 def get_nzb_content(self, connection=None):
     if not connection:
         # create a new connection and close it again
         from connection import Connection
         connection = Connection(connect=True)
         nzb = connection.get_nzb(self)
         connection.disconnect()
         return nzb
     else:
         # leave the connection open
         return connection.get_nzb(self)
开发者ID:alvra,项目名称:django-spotnet,代码行数:13,代码来源:models.py

示例2: IRCServer

# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import disconnect [as 别名]
class IRCServer():
	"""
	class for connecting to an IRC server
	1 server per connection
	"""
	_reconnectTimeout = 300


	def __init__(self, host, port, terminalID = "", password = None):
		self.receivers = {}
		self.quitMessage = ""
		self.password = password
		self.nickNames = Cycle(NICKNAMES)

		self._terminalID = terminalID # shorthand for server in terminal
		self._currentReceiverKey = None
		self._connection = Connection(host, port, self._parseInput)
		self._logger = Logger("%s/%s" % (host, "SERVER"))
		self._clientObject = self._newReceiver(self.nickNames.val())
		self._welcomeEvent = threading.Event()
		self._reconnectEvent = threading.Event()
		self._reconnectEvent.set()

	#-------------------------------------------------------------------------

	def connect(self):
		"""
		connect to the host/port
		raises error on fail
		"""
		try:
			connection = self._connection.connect()
		except Exception as e:
			raise IRCServerError("Connection failed: [%s] %s"%(e.__name__, e))

		if(self.password):
			self.sendRaw("PASS %s" % (self.password))
		self.sendRaw("NICK %s" % self.nickNames.val())
		self.sendRaw("USER %s %s * :%s"%(LOGIN_NAME, socket.gethostname(), 
			REAL_NAME))

		self._welcomeEvent.clear()
		self._welcomeEvent.wait()

	def disconnect(self, message = None):
		if(self.isConnected()):
			if not message:
				message = self.quitMessage
			self.sendCmd("QUIT", None, message)
		self._connection.disconnect()

	def reconnect(self):
		"""
		reconnecting function
		prevents multiple threads from trying to reconnect at once
		pauses all reconnect tries until reconnect succeeds or fails
		"""
		if not self._reconnectEvent.is_set():
			self._reconnectEvent.wait()
		else:
			self._reconnectEvent.clear()
			self.disconnect()
			error = None
			for timer in range(5, self._reconnectTimeout, 15):
				self.log("Reconnecting...")
				try:
					self.connect()
				except Exception as e:
					error = e
					time.sleep(timer)
				else:
					break
			else:
				self.logE("Reconnect failed after %ds: %s"%(timer/60, error))
			self._reconnectEvent.set()

	#-------------------------------------------------------------------------

	def sendRaw(self, data):
		"""sends raw data strings to the server connection"""
		try:
			self._connection.send(data.rstrip())
		except Exception as e:
			self.reconnect()

			self.logE("Data send failed: %s" % e)

	def sendCmd(self, command, meta=None, *message): # TODO limit message length my receiver's full [email protected]
		"""
		sends command with optional meta data and message
		will split messages to ensure they're under the maximum length
		"""
		if meta:
			if isinstance(meta, list):
				meta = " ".join(meta)
			command = "%s %s" % (command, meta)
		if message:
			msg = " ".join(list(message))
			strLim = MESSAGE_LENGTH_LIMIT - (len(command) + 2)
			a=0
#.........这里部分代码省略.........
开发者ID:Clarvel,项目名称:Py3bot,代码行数:103,代码来源:IRCserver.py

示例3: Client

# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import disconnect [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):
开发者ID:z0x010,项目名称:switchy,代码行数:70,代码来源:observe.py

示例4: EventListener

# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import disconnect [as 别名]
class EventListener(object):
    '''ESL Listener which tracks FreeSWITCH state using an observer pattern.
    This implementation utilizes a background event loop (single thread)
    and a receive-only esl connection.

    The main purpose is to enable event oriented state tracking of various
    slave process objects and call entities.
    '''
    id_var = 'switchy_app'
    id_xh = utils.xheaderify(id_var)

    HOST = '127.0.0.1'
    PORT = '8021'
    AUTH = 'ClueCon'

    def __init__(self, host=HOST, port=PORT, auth=AUTH,
                 session_map=None,
                 bg_jobs=None,
                 rx_con=None,
                 call_corr_var_name='variable_call_uuid',
                 call_corr_xheader_name='originating_session_uuid',
                 autorecon=30,
                 max_limit=float('inf'),
                 # proxy_mng=None,
                 _tx_lock=None):
        '''
        Parameters
        ----------
        host : string
            Hostname or ip of the FS engine server to listen to
        port : string
            Port on which the FS server is offering an esl connection
        auth : string
            Authentication password for connecting via esl
        call_corr_var_name : string
            Name of the freeswitch variable (without the 'variable_' prefix)
            to use for associating sessions into calls (see _handle_create).
        call_corr_xheader_name : string
            Name of an Xheader which can be used to associate sessions into
            calls.
            This is useful if an intermediary device such as a B2BUA is being
            tested and is the first hop receiving requests. Note in
            order for this association mechanism to work the intermediary
            device must be configured to forward the Xheaders it recieves.
            (see `self._handle_create` for more details)
        autorecon : int, bool
            Enable reconnection attempts on server disconnect. An integer
            value specifies the of number seconds to spend re-trying the
            connection before bailing. A bool of 'True' will poll
            indefinitely and 'False' will not poll at all.
        '''
        self.server = host
        self.port = port
        self.auth = auth
        self._sessions = session_map or OrderedDict()
        self._bg_jobs = bg_jobs or OrderedDict()
        self._calls = OrderedDict()  # maps aleg uuids to Sessions instances
        self.hangup_causes = Counter()  # record of causes by category
        self.failed_sessions = OrderedDict()
        self._handlers = self.default_handlers  # active handler set
        self._unsub = ()
        self.consumers = {}  # callback chains, one for each event type
        self._waiters = {}  # holds events being waited on
        self._blockers = []  # holds cached events for reuse
        # store up to the last 10k of each event type
        self.events = defaultdict(functools.partial(deque, maxlen=1e3))

        # constants
        self.autorecon = autorecon
        self._call_var = None
        self.call_corr_var = call_corr_var_name
        self.set_xheader_var(call_corr_xheader_name)
        self.max_limit = max_limit
        self._id = utils.uuid()

        # if a mng is provided then assume this listener will
        # be instantiated as a shared object and thus will require
        # at least one shared lock for the tx connection (since
        # it is used by internally by Session instances)
        # if proxy_mng:
        # self._tx_lock = proxy_mng.Lock() if proxy_mng else None
        # self._tx_lock = _tx_lock
        self._shared = False

        # sync
        self._exit = mp.Event()  # indicate when event loop should terminate
        self._lookup_blocker = mp.Event()  # used block event loop temporarily
        self._lookup_blocker.set()
        self.log = utils.get_logger(utils.pstr(self))
        self._epoch = self._fs_time = 0.0

        # set up contained connections
        self._rx_con = rx_con or Connection(self.server, self.port, self.auth)
        self._tx_con = Connection(self.server, self.port, self.auth)

        # mockup thread
        self._thread = None
        self.reset()

    def __dir__(self):
#.........这里部分代码省略.........
开发者ID:z0x010,项目名称:switchy,代码行数:103,代码来源:observe.py

示例5: Pusher

# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import disconnect [as 别名]
class Pusher():
    def __init__(self, applicationKey, encryption=False, secret=None, userdata={}):
        self.channels = {}

        self.secret = secret

        self.userdata = userdata

        self.host = "ws.pusherapp.com"
        self.encryption = encryption
        if self.encryption:
            self.protocol = "wss"
            self.port = "443"
        else:
            self.protocol = "ws"
            self.port = "80"

        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)

        thread.start_new_thread(self.connection._connect, ())

    def disconnect(self):
        self.connection.disconnect()
        self.channels = {}

    def subscribe(self, channelName): 
        data = {}
        data['channel'] = 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)

        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.channels[channelName]._handle_event(eventName, data)


    def _generatePrivateAuthKey(self, socket_id,
                                      applicationKey,
                                      channelName,
                                      secret):
        authKey = ""

        if socket_id and applicationKey and channelName and secret:
            stringToSign = "%s:%s" % (socket_id, channelName)
            h = hmac.new(secret, stringToSign, hashlib.sha256)
            authKey = "%s:%s" % (applicationKey, h.hexdigest())

        return authKey

#.........这里部分代码省略.........
开发者ID:nkhajouei,项目名称:PythonPusherClient,代码行数:103,代码来源:__init__.py

示例6: __init__

# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import disconnect [as 别名]
class Bot:
	def __init__(self, config):
		self.config = config
		self.state = STATE.DISCONNECTED
		self.conn = None
		self.last_recv = None
		self.awaiting_pong = False

		self.handlers = {
			'PING': self.handle_ping,
			'376': self.handle_motd, # RPL_ENDOFMOTD
			'422': self.handle_motd, # ERR_NOMOTD
			'NOTICE': self.handle_notice,
			'MODE': self.handle_mode,
			'PRIVMSG': self.handle_privmsg,
		}

		self.scripts = defaultdict(list)

	def __str__(self):
		return '<Bot: %s/%s>' % (self.config.host, self.config.nick)

	def exception(self, line):
		exc_type, exc_value, exc_tb = sys.exc_info()
		exc_list = traceback.format_exception(exc_type, exc_value, exc_tb)
		self.log(line + '\n' + ''.join(exc_list))

		path, lineno, method, code = traceback.extract_tb(exc_tb)[-1]
		path = os.path.relpath(path)
		exc_name = exc_type.__name__
		notice = '%s:%s():%d %s: %s' % (path, method, lineno, exc_name, exc_value)
		if code is not None:
			notice += ' | ' + code[:50]
		self.notice(config.settings['owner'], notice)

	def log(self, text):
		log.write('%s/%s: %s' % (self.config.host, self.config.nick, text))

	def connect(self):
		host = self.config.host
		port = self.config.port
		self.log('connecting to port %d...' % port)
		self.last_recv = time.time()
		self.awaiting_pong = False
		if not self.conn:
			self.conn = Connection()
		fd, error = self.conn.connect(host, port)
		if error:
			self.log(error)
			self.state = STATE.DISCONNECTED
		else:
			self.state = STATE.CONNECTING
		self.handle_notice(None)
		return fd

	def handle(self):
		for line in self.conn.recv():
			msg = ServerMessage(line)
			handler = self.handlers.get(msg.command)
			if handler:
				try:
					handler(msg)
				except:
					self.exception(line)
		self.last_recv = time.time()

	def check_disconnect(self, ts):
		time_since = ts - self.last_recv
		ping_timeout_wait = config.PING_INTERVAL + config.PING_TIMEOUT
		if time_since > ping_timeout_wait:
			self.log('no reply from server in %ds' % ping_timeout_wait)
			self.disconnect()
			return True
		elif time_since > config.PING_INTERVAL and not self.awaiting_pong and self.state == STATE.IDENTIFIED:
			# don't let the server's reply to ping reset last_recv unless we're fully
			# identified lest we get stuck forever in a partially-connected state
			self.ping()

	def nick(self, new_nick):
		self.conn.send('nick', new_nick)

	def join(self, channel):
		self.conn.send('JOIN', channel)

	def part(self, channel):
		self.conn.send('PART', channel)

	def say(self, target, message):
		self.conn.send('PRIVMSG', target, ':'+message)

	def notice(self, target, message):
		self.conn.send('NOTICE', target, ':'+message)

	def ctcp_reply(self, target, *args):
		self.notice(target, '%c%s%c' % (1, ' '.join(args), 1))

	def ping(self):
		self.conn.send('PING', 'pbot')
		self.awaiting_pong = True

#.........这里部分代码省略.........
开发者ID:Frostbite,项目名称:pbot,代码行数:103,代码来源:bot.py

示例7: CoinalyticsPusher

# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import disconnect [as 别名]
class CoinalyticsPusher(object):
    host = "coinalytics.com"

    client_id = 'PythonPusherClient'
    protocol = 6

    def __init__(self, key, secure=False, secret=None, user_data=None, log_level=logging.INFO):
        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), log_level=log_level)

    def connect(self):
        """Connect to Pusher"""
        thread.start_new_thread(self.connection.run, ())

    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 = ""

#.........这里部分代码省略.........
开发者ID:Coinalytics,项目名称:PythonPusherClient,代码行数:103,代码来源:__init__.py

示例8: __init__

# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import disconnect [as 别名]
class Boteco:

    def __init__(self, host, port, nick):
        self.state = BotState()
        self.state._host = host
        self.state._port = port
        self.state._nick = nick
        
        self._command = BotCommands()
        self._is_connected = False

    def connect(self):
        if self._is_connected:
            return

        self._sock = Connection()
        self._sock.connect(self.state._host, self.state._port)
        
        while 1:
            data = self._read_line()
            if data == "":
                break
                
            print(data)

        self._send_command("NICK " + self.state._nick)
        self._send_command("USER " + self.state._nick + " myhost myhost :" + self.state._nick)

        # Read the whole MOTD and whatever else there is and simply ignore
        while 1:
            data = self._read_line()
            if data == "":
                return
                
            print(data)

    def get_socket(self):
        return self._sock

    def join_channel(self, channel):
        self._command.join(channel)
      
    def is_connected(self):
        return self._sock.is_connected

    def parse(self, data):
        ircmsg = IRCMessage(data)

        if ircmsg.msg_type == "":
            return

        if ircmsg.msg_type == "PING":
            self._send_command("PONG " + ircmsg.from_host)
            
        elif ircmsg.msg_type == "ERROR":
            self._sock.disconnect()

        elif ircmsg.msg_type == "JOIN":
            self._handle_join(ircmsg)

        elif ircmsg.msg_type == "PRIVMSG":
            self._handle_privmsg(ircmsg)


    def _read_line(self):
        return self._sock.read_line()

    def _send_command(self, command):
        self._command.send_command(command)

    def _send_message(self, to, msg):
        self._command.send_message(to, msg)

    def _handle_privmsg(self, ircmsg):
        if ircmsg.cmd == "":
            return

        self._command.execute(ircmsg)

    # TODO: Might want to rewrite this...
    def _handle_join(self, ircmsg):

        # Is it the bot joining?
        if ircmsg.from_nick == self.state._nick:
            people_on_channel = []
            joined_channel = ircmsg.to
            
            while 1:
                data = self._read_line()
                print(data)
                
                tokens = [el.strip() for el in data.split(" ")]

                if tokens[1] == "353":
                    for i in tokens[5:]:
                        people_on_channel.append(i.strip(":"))
                        self.state.joined_channel(ircmsg.to, i.strip(":"))

                        print("Joined channel %s\n" % ircmsg.to)
                    
#.........这里部分代码省略.........
开发者ID:typoon,项目名称:boteco,代码行数:103,代码来源:boteco.py

示例9: __init__

# 需要导入模块: from connection import Connection [as 别名]
# 或者: from connection.Connection import disconnect [as 别名]

#.........这里部分代码省略.........
        self.send_command(line)

    def join(self, channel):
        ircmsg = IRCMessage("")

        ircmsg.msg_type = "JOIN"
        ircmsg.cmd = "join"
        ircmsg.args = channel

        self._join(ircmsg)

    def _read_line(self):
        return self._conn.read_line()

    def _list_modules(self, ircmsg):
        line  = "Loaded modules: "

        if len(self._modules) > 0:
            loaded_modules = [m.__name__[m.__name__.find(".")+1:] for m in self._modules]
            line += ", ".join(loaded_modules)
        else:
            line  = "No modules have been loaded yet"

        self.send_message(ircmsg.reply_to, line)

    def _quit(self, ircmsg):

        if not ircmsg.args:
            line = "QUIT :%s" % " ".join(ircmsg.args)
        else:
            line = "QUIT :Don't kill meeeeeeeeeeeeeeeeee"

        self.send_command(line)
        self._conn.disconnect()

    def _reload_modules(self, ircmsg):
        '''
        Reloads specified module. If no module is specified, reload them all
        If module specified has not been loaded yet, load it
        '''

        reloaded_modules = []
        module_found = False

        if len(ircmsg.args) > 0:
            for i in ircmsg.args:
                mod_name = "commands.%s" % i
                
                try:
                    for j in self._modules:
                        if mod_name == j.__name__:
                            imp.reload(j)
                            reloaded_modules.append(i)
                            module_found = True

                    if module_found == False:
                        mod = importlib.import_module(mod_name)
                        reloaded_modules.append(i)
                        self._modules.append(mod)
                        
                except:
                    msg = "Module %s cannot be reloaded (%s)" % (i, sys.exc_info())
                    self.send_message(ircmsg.reply_to, msg)
        else:
            self.load_modules()  # Loads any new modules that have been created
            
开发者ID:typoon,项目名称:boteco,代码行数:69,代码来源:botcommands.py


注:本文中的connection.Connection.disconnect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。