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


Python Stream.connect方法代码示例

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


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

示例1: _on_decode_error

# 需要导入模块: from stream import Stream [as 别名]
# 或者: from stream.Stream import connect [as 别名]
    def _on_decode_error(self, received):
        self._disable_heartbeat()
        self._stream._encoders = []
        backend = Stream(prefix="SIMPLE")

        def tunnel_ready_to_send(_):
            backend.start_receiving()

        def tunnel_send_buffer_full(_):
            backend.stop_receiving()

        def tunnel_received(_, data, _addr):
            backend.send(data)
            return backend.is_ready_to_send()

        def tunnel_closed(_):
            backend.close()

        def backend_received(_, data, _addr):
            self._stream.send(data)
            return self._stream.is_ready_to_send()

        def backend_closed(_self):
            self._stream.close()

        self._stream.set_on_ready_to_send(tunnel_ready_to_send)
        self._stream.set_on_send_buffer_full(tunnel_send_buffer_full)
        self._stream.set_on_received(tunnel_received)
        self._stream.set_on_closed(tunnel_closed)
        backend.set_on_received(backend_received)
        backend.set_on_closed(backend_closed)
        if received is not None and len(received) > 0:
            backend.send(received)
        backend.connect(UNKNOWN_CONN_ADDR, UNKNOWN_CONN_PORT)
开发者ID:binasc,项目名称:utils,代码行数:36,代码来源:tunnel.py

示例2: run

# 需要导入模块: from stream import Stream [as 别名]
# 或者: from stream.Stream import connect [as 别名]
    def run(self):
        """Starts the loop"""
        print (NICK)
        print ("Bot.run()")

        Stream.connect((NETWORK, PORT))
        # receive buffer, and connect setup
        Stream.recv(4096)  # rcv buffer
        Stream.send("NICK " + NICK + "\r\n")
        Stream.send("USER magikarp magikarp magikarp :magikarp\r\n")

        # main loop
        while True:
            data = Stream.recv(4096)  # get lines
            print (data)  # print lines

            # Basic init commands after server connection
            if data.find("MODE " + NICK + " +i") != -1:
                Stream.send("JOIN " + CHAN + "\r\n")
                # Stream.send('PRIVMSG ' + CHAN + ' :Morning, ' + CHAN + '\r\n')

            # Constant ping lookout
            if data.find("PING") != -1:
                Stream.send("PONG " + data.split()[1] + "\r\n")

            elif data.find("PRIVMSG") != -1:  # if there is a PRIVMSG in data then parse it
                message = ":".join(data.split(":")[2:])  # split the command from the message
                print (message)

                function = message.split()[0]  # split the massage to get function name

                if (
                    message.lower().find("awesome") != -1 and not function.find("^") != -1
                ):  # split the massage to get function name:
                    nick = data.split("!")[0].replace(":", "")  # snatch the nick issuing the command
                    destination = "".join(data.split(":")[:2]).split(" ")[-2]
                    # Stream.send('PRIVMSG ' + destination + ' :Yeah ' + nick + '! Awesome!\r\n')

                if Parser().ContainsAny(message, ["http", "http", "www", ".com", ".org", ".eu"]) == 1:
                    nick = data.split("!")[0].replace(":", "")  # snatch the nick issuing the command
                    destination = "".join(data.split(":")[:2]).split(" ")[-2]
                    arg = data.split()
                    args = []
                    for index, item in enumerate(arg):  # for every index and item in arg
                        if (
                            index > 2
                            and Parser().ContainsAny(item, ["http", "http", "www", ".com", ".org", ".eu"]) == 1
                        ):
                            n = 1
                            if args == []:
                                # item = (item.split(':', 1)[1])
                                args.append(item)
                            else:
                                args.append(" " + item)
                                n += 1

                    args.append("\n")
                    print args

                    if args != "":
                        fileObj = open(FILEDIR + "/botlinks", "a")
                        fileObj.write("[" + destination + "] " + CurrentTimeString() + " " + nick + ": ")
                        for i in args:
                            fileObj.write(i)
                        fileObj.close()

                if message.lower().find("^") != -1:  # if the message contains the chan name
                    nick = data.split("!")[0].replace(":", "")  # snatch the nick issuing the command
                    print ("nick: " + nick)
                    destination = "".join(data.split(":")[:2]).split(" ")[-2]
                    print ("dest: " + destination)
                    function = message.split()[0]  # split the massage to get function name
                    print ("function: " + function)
                    print ("The function called is " + function + " from " + nick)  # command and the caller
                    arg = data.split()  # arg[0] is the actual comand

                    args = ""
                    for index, item in enumerate(arg):  # for every index and item in arg
                        if index > 3:
                            if args == "":
                                args = item
                            else:
                                args += " " + item
                    print (args)

                    if function == "^credits":  # if function is equal to ^credits
                        Stream.send(
                            "PRIVMSG "
                            + destination
                            + " :"
                            + nick
                            + ": I'm developed by magikmw - http://github.com/magikmw/magikarp \r\n"
                        )

                    elif function == "^say":
                        if args != "":
                            # Stream.send('PRIVMSG ' + destination + ' :' + args + '\r\n')
                            Stream.send(
                                "PRIVMSG "
                                + destination
#.........这里部分代码省略.........
开发者ID:magikmw,项目名称:magikarp,代码行数:103,代码来源:bot.py

示例3: RedisClient

# 需要导入模块: from stream import Stream [as 别名]
# 或者: from stream.Stream import connect [as 别名]
class RedisClient(EventEmitter):
    def __init__(self,*args,**options):
        self.host = "127.0.0.1" if len(args) < 2 else args[1]
        self.port = 6379 if len(args) < 1 else args[0]
        
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)

        self.options = Jso(options)
        self.stream = Stream(sock,io_loop=self.options.io_loop)
        self.stream.connect((self.host,self.port))


        self.connected = False
        self.ready = False
        self.send_anyway = True
        self.connections = 0
        self.attempts = 1
        self.command_queue = collections.deque()
        self.offline_queue = collections.deque()
        self.commands_sent = 0
        self.retry_delay = .25
        self.retry_timer = None
        self.emitted_end = False
        self.current_retry_delay = self.retry_delay
        self.retry_backoff = 1.7
        self.subscriptions = False
        self.monitoring = False
        self.closing = False
        self.server_info = Jso()
        self.auth_pass = None
        self.encoding = self.options.encoding or 'utf-8'
        self.encoding_error = self.options.encoding_error or 'strict'

        self.reply_parser = Parser()
        self.reply_parser.on("reply_error",self.return_error)
        self.reply_parser.on("reply",self.return_reply)
        self.reply_parser.on("error",self.return_error_unrecoverable)

        self.stream.on("connect",self.on_connect)
        self.stream.on("data",self.on_data)
        #TODO: create error event
        #self.stream.on("error",self.on_error)
        self.stream.on("close",functools.partial(self.connection_gone,"close"))
        self.stream.on("end",functools.partial(self.connection_gone,"end"))
        

    #### Parser Callbacks ####
        
        
    def return_error_unrecoverable(self,err):
        self.emit("error",ReplyParserError(str(err)))

    def return_error(self,err):
        command_obj = self.command_queue.popleft()

        if not self.subscriptions and len(self.command_queue) == 0:
            self.emit("idle")

        if command_obj and operator.isCallable(command_obj.callback):
            command_obj.call_callback(None,err)
        else:
            logging.debug("tornado-redis: no callback to send error: %s" % str(err))
            #IOLoop.instance().add_callback(functools.partial(self.raise_error,err))


    def return_reply(self,reply):
        command_obj = self.command_queue.popleft() if len(self.command_queue) > 0 else None

        if not self.subscriptions and len(self.command_queue) == 0:
            self.emit("idle")

        if command_obj and not command_obj.sub_command:
            if operator.isCallable(command_obj.callback):
                if reply and command_obj.command.lower() == 'hgetall':
                    i = 0
                    obj = Jso()
                    while i < len(reply):
                        key = str(reply[i])
                        val = reply[i+1]
                        obj[key] = val
                    reply = obj

                command_obj.call_callback(reply,None)
            else:
                logging.debug("no callback for reply: %s" % reply)

        elif self.subscriptions or (command_obj and command_obj.sub_command):
            if isinstance(reply,list):
                if reply[0] in ["subscribe","unsubscribe","psubscribe"] and reply[2] == 0:
                    self.subscriptions = False
                    logging.debug("All subscriptions removed, exiting pub/sub mode")
                if reply[0] not in ["message","pmessage","subscribe","unsubscribe","psubscribe"]:
                    raise TypeError("subscriptions are active but unknow reply type %s" % reply[0])

                try:
                    self.emit(*reply)
                except Exception:
                     logging.error("Uncaught exceptions in subscriptions.",
                                   exc_info=True)
            elif not self.closing:
#.........这里部分代码省略.........
开发者ID:joshrtay,项目名称:tornado_redis,代码行数:103,代码来源:client.py

示例4: Tunnel

# 需要导入模块: from stream import Stream [as 别名]
# 或者: from stream.Stream import connect [as 别名]
class Tunnel(object):
    _TCP_INITIAL_DATA = 0
    _TCP_FIN_DATA = 1
    _TCP_CLOSED_DATA = 2
    _UDP_INITIAL_DATA = 3
    _UDP_CLOSED_DATA = 4
    _TUN_INITIAL_DATA = 5
    _PAYLOAD = 10
    _HEARTBEAT = 100

    _static_handlers = {
        _HEARTBEAT: (lambda _, __, ___: None)
    }

    @staticmethod
    def set_tcp_initial_handler(handler):
        Tunnel._static_handlers[Tunnel._TCP_INITIAL_DATA] = handler

    @staticmethod
    def set_tcp_fin_received_handler(handler):
        Tunnel._static_handlers[Tunnel._TCP_FIN_DATA] = handler

    @staticmethod
    def set_tcp_closed_handler(handler):
        Tunnel._static_handlers[Tunnel._TCP_CLOSED_DATA] = handler

    @staticmethod
    def set_udp_initial_handler(handler):
        Tunnel._static_handlers[Tunnel._UDP_INITIAL_DATA] = handler

    @staticmethod
    def set_udp_closed_handler(handler):
        Tunnel._static_handlers[Tunnel._UDP_CLOSED_DATA] = handler

    @staticmethod
    def set_tun_initial_handler(handler):
        Tunnel._static_handlers[Tunnel._TUN_INITIAL_DATA] = handler

    def __init__(self, connection=None, connect_to=None):
        self._stream = connection
        self._connect_to = connect_to
        self._on_initial_data = None
        self._on_payload = None
        self._on_stream_closed = None
        self._handlers = self._static_handlers.copy()
        self._handlers.update({
            Tunnel._PAYLOAD: lambda _, id_, data: self._on_payload(self, id_, data)
        })
        self._on_ready_to_send = None
        self._on_send_buffer_full = None
        self._hb_event = None
        self.connections = {}

    def __hash__(self):
        return hash(self._stream)

    def __eq__(self, other):
        if not isinstance(other, Tunnel):
            return False
        return self._stream == other._stream

    def __str__(self):
        return str(self._stream)

    def _send_heartbeat(self):
        self._send_content(Tunnel._HEARTBEAT, None, None)
        self._enable_heartbeat()

    def _enable_heartbeat(self):
        self._hb_event = Event.add_timer(HEARTBEAT_INTERVAL)
        self._hb_event.set_handler(lambda ev: self._send_heartbeat())

    def _disable_heartbeat(self):
        if self._hb_event is not None:
            self._hb_event.del_timer()
            self._hb_event = None

    def _on_fin_received(self):
        self._disable_heartbeat()
        self._stream.close()

    def initialize(self):
        if self._stream is None:
            self._stream = Stream(prefix='TUNNEL')

        # self._stream.set_buffer_size(BUFF_SIZE)
        self._stream.set_tcp_no_delay()

        self._stream.append_send_handler(obscure.pack_data)
        self._stream.append_send_handler(obscure.random_padding)
        # self._stream.append_send_handler(obscure.gen_aes_encrypt())
        self._stream.append_send_handler(obscure.gen_xor_encrypt())
        # self._stream.append_send_handler(obscure.base64_encode)
        self._stream.append_send_handler(obscure.gen_http_encode(self._connect_to is not None))
        self._stream.append_receive_handler(obscure.gen_http_decode(self._connect_to is not None))
        # self._stream.append_receive_handler(obscure.base64_decode)
        self._stream.append_receive_handler(obscure.gen_xor_decrypt())
        # self._stream.append_receive_handler(obscure.gen_aes_decrypt())
        self._stream.append_receive_handler(obscure.unpad_random)
        self._stream.append_receive_handler(obscure.unpack_data)
#.........这里部分代码省略.........
开发者ID:binasc,项目名称:utils,代码行数:103,代码来源:tunnel.py


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