def test_notif(self):
     # simulate the daemon already having created
     # a valid token (which it usually does when
     # starting the WalletService:
     self.daemon.wss_factory.valid_token = encoded_token
     self.client_factory = WebSocketClientFactory("ws://127.0.0.1:" +
                                                  str(self.wss_port))
     self.client_factory.protocol = ClientTProtocol
     self.client_connector = connectWS(self.client_factory)
     d = task.deferLater(reactor, 0.1, self.fire_tx_notif)
     # create a small delay between the instruction to send
     # the notification, and the checking of its receipt,
     # otherwise the client will be queried before the notification
     # arrived:
     d.addCallback(self.wait_to_receive)
     return d
Пример #2
0
    def _create_client_service(self, nodeurl, api_token):
        url = parse(nodeurl)
        wsurl = url.replace(scheme="ws").child("private", "logs", "v1")

        factory = WebSocketClientFactory(
            url=wsurl.to_uri().to_text(),
            headers={
                "Authorization": "{} {}".format("tahoe-lafs", api_token),
            },
        )
        factory.protocol = TahoeLogReader
        factory.streamedlogs = self

        endpoint = TCP4ClientEndpoint(self._reactor, url.host, url.port)
        client_service = ClientService(endpoint, factory, clock=self._reactor)
        return client_service
Пример #3
0
    def _start_socket(self,
                      path,
                      callback,
                      update_time=WEBSOCKET_UPDATE_1SECOND):
        if update_time != WEBSOCKET_UPDATE_1SECOND:
            path = '{}@{}'.format(path, update_time)

        if path in self._conns:
            return False

        factory = WebSocketClientFactory(BINANCE_STREAM_URL + path)
        factory.protocol = BinanceClientProtocol
        factory.callback = callback
        context_factory = ssl.ClientContextFactory()

        self._conns[path] = connectWS(factory, context_factory)
        return path
Пример #4
0
    def stop_socket(self, conn_key):
        """Stop a websocket given the connection key
        :param conn_key: Socket connection key
        :type conn_key: string
        :returns: connection key string if successful, False otherwise
        """
        if conn_key not in self._conns:
            return

        # disable reconnecting if we are closing
        self._conns[conn_key].factory = WebSocketClientFactory(self.STREAM_URL + 'tmp_path')
        self._conns[conn_key].disconnect()
        del(self._conns[conn_key])

        # check if we have a user stream socket
        if len(conn_key) >= 60 and conn_key[:60] == self._user_listen_key:
            self._stop_user_socket()
Пример #5
0
    def connect_to_websocket(self):
        logger.info('Connecting to websocket')

        factory = WebSocketClientFactory(
            'wss://ws-feed.exchange.coinbase.com',
            debug=False,
        )

        # This actually creates a new Instance of CoinbaseOrderbook.
        factory.protocol = type(self)

        if factory.isSecure:
            context_factor = ssl.ClientContextFactory()
        else:
            context_factor = None

        connectWS(factory, context_factor)
Пример #6
0
    def test():
        import sys
        import ssl
        from twisted.python import log
        from twisted.internet import reactor, ssl
        import numpy as np

        log.startLogging(sys.stdout)
        numb = np.random.randint(0, 1000)
        server_num = np.random.randint(0, 200)
        randstr = str(uuid.uuid1())[:8]
        url = f"wss://stream{server_num}.forexpros.com/echo/{numb}/{randstr}/websocket"
        factory = WebSocketClientFactory(url)   # , #headers=headers)
        factory.setProtocolOptions(autoPingInterval=1)
        factory.protocol = InvestingdotcomProtocol.make_subids([1, 2])  # .set_timeout(100)
        connectWS(factory)
        reactor.run()
Пример #7
0
 def onTicker(self, data):
     """
     Called upon reception of the initial 'ticker' data, triggers WebSocket market data subscription
     """
     self.log('onTicker, data[{0}'.format(data))
     ticker = json.loads(data)
     self.log('received ticker from exchange {0}'.format(data))
     price = ticker.get("price", None)
     if price is None:
         self.fatal("could not retrieve price")
     self.basePrice = Decimal(price)
     self.log('retrieved base price for {0}: {1}'.format(
         self.product, self.basePrice))
     self.log('starting websocket connection')
     factory = WebSocketClientFactory(self.wsAddress)
     factory.protocol = CoinbaseWebSocketClient
     factory.coinbaseClient = self
     connectWS(factory)
Пример #8
0
    def __init__(self, url, username, password):
        super(ETPClient, self).__init__()
        log.startLogging(sys.stdout)

        headers = {
            'Authorization':
            'Basic {}'.format(
                b64encode(b'ilab.user:n@6C5rN!').decode("utf-8"))
        }

        factory = WebSocketClientFactory(
            "wss://witsmlstudio.pds.software/staging/api/etp",
            headers=headers,
            protocols=["energistics-tp"])
        self.factory = factory

        self.factory.protocol = ETPClientProtocol

        self.factory.on_etp_message = self.on_etp_message
Пример #9
0
def runpatch(patch):
    print 'running patch'
    print patch
    factory = WebSocketClientFactory("ws://%s:7682/ws" % addr,
                                     debug=options.debug,
                                     protocols=['shell'])
    factory.info = {
        'cmd': 'build.py',
        'repo': 'git://github.com/zedblue/leds',
        'dir': '',
        'username': '******',
        'branch': 'master',
        'boardname': 'zedboard',
        'listfiles': 0,
        'update': 0,
        'patch': patch
    }
    factory.protocol = ShellClientProtocol
    reactor.connectTCP(addr, 7682, factory)
Пример #10
0
    def stop_socket(self, conn_key):
        """Stop a websocket given the connection key

        Parameters
        ----------
        conn_key : str
            Socket connection key

        Returns
        -------
        str, bool
            connection key string if successful, False otherwise
        """
        if conn_key not in self._conns:
            return

        # disable reconnecting if we are closing
        self._conns[conn_key].factory = WebSocketClientFactory(self.STREAM_URL)
        self._conns[conn_key].disconnect()
        del self._conns[conn_key]
Пример #11
0
def listen(pid, q):
    print("{} STARTING".format(pid))
    # Import in method.. fix side effect of tornado
    from app.cfxws.exchange import Binance

    def act(_, msg):
        q.put(str(msg))

    def handle_response(_, response, type):
        return response

    factory = WebSocketClientFactory("wss://stream.binance.com:9443/ws/btcusdt@depth5")

    MyWs = WSClient
    MyWs._handle_response = handle_response
    MyWs.handle_method = act
    factory.protocol = MyWs
    contextFactory = ssl.ClientContextFactory()
    connectWS(factory, contextFactory)
    reactor.run()
Пример #12
0
def create_websocket_client(app, websocket_id, local=False, callback=False):
    if local:

        class PytigonClientProtocol(PytigonClientProtocolBase):
            def __init__(self, app):
                self.app = app
                self.websocket_id = websocket_id
                self.input_queue = asyncio.Queue()
                self.callbacks = []
                self.status = 1

            async def send_message(self, msg):
                await self.input_queue.put(json_dumps(msg))

        app.websockets[websocket_id] = PytigonClientProtocol(app)

    else:

        class PytigonClientProtocol(PytigonClientProtocolBase,
                                    WebSocketClientProtocol):
            def __init__(self):
                nonlocal app, websocket_id
                PytigonClientProtocolBase.__init__(self)
                WebSocketClientProtocol.__init__(self)
                self.app = app
                self.websocket_id = websocket_id
                app.websockets[websocket_id] = self
                self.status = 0

            def send_message(self, msg):
                super().sendMessage(json_dumps(msg).encode("utf-8"))

        ws_address = app.base_address.replace("http",
                                              "ws").replace("https", "wss")
        ws_address += websocket_id
        factory = WebSocketClientFactory(ws_address)
        factory.protocol = PytigonClientProtocol
        connectWS(factory)

    if callback:
        app.add_websoket_callback(websocket_id, callback)
Пример #13
0
 def onConnect(self, request):
     """
     Websocket (not HTTP) connection start
     """
     self.request = request
     print("Client connecting: {0}".format(self.request))
     # this might be a valid request, so we'll start a BACKEND connection
     backendurl = os.environ.get("BACKEND")
     if self.request.params:
         # add the GET parameters to the backend request
         backendurl += "?" + parse.urlencode(self.request.params,
                                             doseq=True)
     print("{1}: starting proxy backend connection attempt: {0}".format(
         backendurl, self.request.peer))
     self.proxyfactory = WebSocketClientFactory(url=backendurl)
     self.proxyfactory.setProtocolOptions(autoPingInterval=10,
                                          autoPingTimeout=3)
     self.proxyfactory.protocol = WebsocketInfoProxyProtocol
     self.proxyfactory.proxyproto = None
     # this will be None until the connection to BACKEND
     # is successfully connected
     self.proxyfactory.messagecache = None
     self.proxyfactory.clientconnection = self
     sslfactory = None
     if os.environ.get("SSL_CLIENT_CERT", False) and os.environ.get(
             "SSL_CLIENT_KEY", False):
         cert = ssl.Certificate.loadPEM(os.environ.get("SSL_CLIENT_CERT"))
         key = ssl.KeyPair.load(os.environ.get("SSL_CLIENT_KEY"),
                                crypto.FILETYPE_PEM)
         privatecert = ssl.PrivateCertificate.fromCertificateAndKeyPair(
             cert, key)
         print("{1}: loaded client cert {0}".format(privatecert,
                                                    self.request.peer))
         if os.environ.get("SSL_CLIENT_CA", False):
             cacerts = ssl.Certificate.loadPEM(
                 os.environ.get("SSL_CLIENT_CA"))
             print("{1}: CA cert {0}".format(cacerts, self.request.peer))
             sslfactory = privatecert.options(cacerts)
         else:
             sslfactory = privatecert.options()
     connectWS(self.proxyfactory, contextFactory=sslfactory)
Пример #14
0
    def connect(self):
        factory = WebSocketClientFactory("ws://%s:%s/ws/" %
                                         (self.host, self.port),
                                         debug=False)
        factory.noisy = True
        factory.protocol = MdcloudWebsocketClientProtocol
        factory.protocol.client = self

        self.onc = defer.Deferred()

        key_path = os.path.expanduser('~/.mcloud/%s.key' % self.host)
        crt_path = os.path.expanduser('~/.mcloud/%s.crt' % self.host)

        class NoKeyError(Exception):
            pass

        try:
            if not self.no_ssl and self.host != '127.0.0.1':

                if not os.path.exists(key_path):
                    raise NoKeyError(
                        'Key for server "%s" not found in file "%s"' %
                        (self.host, key_path))

                if not os.path.exists(crt_path):
                    raise NoKeyError(
                        'Key for server "%s" not found in file "%s"' %
                        (self.host, crt_path))

                from mcloud.ssl import CtxFactory

                reactor.connectSSL(self.host, self.port, factory,
                                   CtxFactory(key_path, crt_path))
            else:
                reactor.connectTCP(self.host, self.port, factory)
        except NoKeyError:

            print 'No key found - fallback to no-ssl'
            reactor.connectTCP(self.host, self.port, factory)

        return self.onc
Пример #15
0
def main():

    global command_library
    command_library = CommandLibrary()
    address = "ws://" + 'localhost'
    keyboard = Keyboard_Input()
    stdio.StandardIO(keyboard)
    multicast = reactor.listenMulticast(udpbport,
                                        MulticastProtocol(),
                                        listenMultiple=True)

    factory = WebSocketClientFactory(address + ":8084", debug=False)
    factory.setProtocolOptions(failByDrop=False)
    factory.protocol = MyClientProtocol
    try:
        connectWS(factory)
        command_library.factory = factory
        command_library.multicast = multicast
        factory.command_library = command_library
    except twisted.internet.error.CannotListenError:
        print "Can't listen"
Пример #16
0
    def test_cbor_raw(self):
        test_client_received = []

        class TestClientProtocol(WebSocketClientProtocol):
            def onOpen(self):
                self.sendMessage(
                    json.dumps({
                        'op': 'subscribe',
                        'topic': TOPIC,
                        'compression': 'cbor-raw',
                    }))

            def onMessage(self, payload, binary):
                test_client_received.append(payload)

        protocol = os.environ.get('PROTOCOL')
        port = rospy.get_param('/rosbridge_websocket/actual_port')
        url = protocol + '://127.0.0.1:' + str(port)

        factory = WebSocketClientFactory(url)
        factory.protocol = TestClientProtocol
        reactor.connectTCP('127.0.0.1', port, factory)

        pub = rospy.Publisher(TOPIC, String, queue_size=1)

        def publish_timer():
            rospy.sleep(WARMUP_DELAY)
            pub.publish(String(STRING))
            rospy.sleep(TIME_LIMIT)
            reactor.stop()

        reactor.callInThread(publish_timer)
        reactor.run()

        self.assertEqual(len(test_client_received), 1)
        websocket_message = decode_cbor(test_client_received[0])
        self.assertEqual(websocket_message['topic'], TOPIC)
        buff = io.BytesIO()
        String(STRING).serialize(buff)
        self.assertEqual(websocket_message['msg']['bytes'], buff.getvalue())
Пример #17
0
 def ws_keep_alive(self):
     ssl_context = ssl.SSLContext()
     ssl_context.check_hostname = False
     ssl_context.verify_mode = ssl.CERT_NONE
     ua_file = open("user_agents.json", "r+")
     user_agents = json.load(ua_file)
     ua_file.close()
     ws_url = "wss://api.irccloud.com/"
     ws_origin = "https://api.irccloud.com"
     irc_cloud_header = {
         "Connection": "Upgrade",
         "Host": "api.irccloud.com",
         "Origin": ws_origin,
         "User-Agent": random.choice(user_agents),
         "Cookie": "session={0}".format(irccloud.SessionId),
         "Sec-WebSocket-Key": self.get_secure_key(),
         "Sec-WebSocket-Version": "13",
         "Upgrade": "WebSocket"
     }
     factory = WebSocketClientFactory(ws_url, headers=irc_cloud_header)
     connectWS(factory)
     reactor.run()
Пример #18
0
def main(reactor):

    from twisted.python import log
    log.startLogging(sys.stdout)

    tahoe_dir = "testgrid/alice"
    cfg = read_config(tahoe_dir, "portnum")

    token = cfg.get_private_config("api_auth_token").strip()
    webport = cfg.get_config("node", "web.port")
    if webport.startswith("tcp:"):
        port = webport.split(':')[1]
    else:
        port = webport

    factory = WebSocketClientFactory(
        url=u"ws://127.0.0.1:{}/private/logs/v1".format(port),
        headers={
            "Authorization": "tahoe-lafs {}".format(token),
        }
    )
    factory.on_open = Deferred()
    factory.on_close = Deferred()

    factory.protocol = TahoeLogProtocol

    endpoint = HostnameEndpoint(reactor, "127.0.0.1", int(port))
    try:
        port = yield endpoint.connect(factory)
    except ConnectError as e:
        print("Connection failed: {}".format(e))
        return

    print("port: {}".format(port))
    yield factory.on_open
    print("opened")
    yield factory.on_close
    print("closed")
Пример #19
0
    def test_smoke(self):
        protocol = os.environ.get('PROTOCOL')
        port = rospy.get_param('/rosbridge_websocket/actual_port')
        url = protocol + '://127.0.0.1:' + str(port)

        factory = WebSocketClientFactory(url)
        factory.protocol = TestClientProtocol
        reactor.connectTCP('127.0.0.1', port, factory)

        ros_received = []
        TestClientProtocol.received = []
        rospy.Subscriber(A_TOPIC, String, ros_received.append)
        pub = rospy.Publisher(B_TOPIC, String, queue_size=NUM_MSGS)

        def publish_timer():
            rospy.sleep(WARMUP_DELAY)
            msg = String(B_STRING)
            for _ in range(NUM_MSGS):
                pub.publish(msg)

        def shutdown_timer():
            rospy.sleep(WARMUP_DELAY + TIME_LIMIT)
            reactor.stop()

        reactor.callInThread(publish_timer)
        reactor.callInThread(shutdown_timer)
        reactor.run()

        for received in TestClientProtocol.received:
            msg = json.loads(received)
            self.assertEqual('publish', msg['op'])
            self.assertEqual(B_TOPIC, msg['topic'])
            self.assertEqual(B_STRING, msg['msg']['data'])
        self.assertEqual(NUM_MSGS, len(TestClientProtocol.received))

        for msg in ros_received:
            self.assertEqual(A_STRING, msg.data)
        self.assertEqual(NUM_MSGS, len(ros_received))
Пример #20
0
def addnewnode(host):
    ws = "ws://{}:9000".format(host)
    #factory = WebSocketClientFactory(u"ws://127.0.0.1:9000")
    factory = WebSocketClientFactory(ws)
    factory.protocol = MyClientProtocol
    reactor.connectTCP(host, 9000, factory)
Пример #21
0
                senderwallet=x["senderwallet"],
                receiver=x["receiver"],
                prevblockhash=x["prevblockhash"],
                blockhash=x["blockhash"],
                amount=x["amount"],
                nonce=x["nonce"],
                first_timestamp=x["first_timestamp"],
                P2PKH=x["P2PKH"],
                verification=x["verification"])
            newtrans.save()
    print("everyting is up-da-te")



if __name__ == '__main__':
    import sys, argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--host",   help="Please fill ip address")
    args = parser.parse_args()
    syncfirst(args.host)

    ServerFactory = BroadcastServerFactory
    factory = ServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = BroadcastServerProtocol
    reactor.listenTCP(9000, factory)
    ws = "ws://{}:9000".format(args.host)
    factory = WebSocketClientFactory(ws)
    factory.protocol = MyClientProtocol
    reactor.connectTCP(args.host, 9000, factory)
    reactor.run()
Пример #22
0

if __name__ == '__main__':

    if len(sys.argv) < 2:
        print("Need the WebSocket server address, i.e. ws://localhost:9000")
        sys.exit(1)

    if len(sys.argv) > 2 and sys.argv[2] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False

    factory = WebSocketClientFactory(sys.argv[1],
                                     debug=debug,
                                     debugCodePaths=debug)

    factory.protocol = EchoClientProtocol

    # Enable WebSocket extension "permessage-deflate".
    ##

    # The extensions offered to the server ..
    offers = [PerMessageDeflateOffer()]
    factory.setProtocolOptions(perMessageCompressionOffers=offers)

    # Function to accept responses from the server ..
    def accept(response):
        if isinstance(response, PerMessageDeflateResponse):
            return PerMessageDeflateResponseAccept(response)
Пример #23
0
class PingClientProtocol(WebSocketClientProtocol):
    def onOpen(self):
        self.pingsReceived = 0
        self.pongsSent = 0

    def onClose(self, wasClean, code, reason):
        reactor.stop()

    def onPing(self, payload):
        self.pingsReceived += 1
        print("Ping received from {} - {}".format(self.peer,
                                                  self.pingsReceived))
        self.sendPong(payload)
        self.pongsSent += 1
        print("Pong sent to {} - {}".format(self.peer, self.pongsSent))


if __name__ == '__main__':

    log.startLogging(sys.stdout)

    if len(sys.argv) < 2:
        print("Need the WebSocket server address, i.e. ws://127.0.0.1:9000")
        sys.exit(1)

    factory = WebSocketClientFactory(sys.argv[1])
    factory.protocol = PingClientProtocol
    connectWS(factory)

    reactor.run()
Пример #24
0
    def onOpen(self):
        self.sendHello()

    def onMessage(self, payload, isBinary):
        if not isBinary:
            print("Text message received: {}".format(payload.decode('utf8')))
        reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

    if len(sys.argv) < 2:
        print("Need the WebSocket server address, i.e. ws://127.0.0.1:9000")
        sys.exit(1)

    if len(sys.argv) < 3:
        print("Need the Proxy, i.e. 192.168.1.100:8050")
        sys.exit(1)

    proxyHost, proxyPort = sys.argv[2].split(":")
    proxy = {'host': proxyHost, 'port': int(proxyPort)}

    log.startLogging(sys.stdout)

    factory = WebSocketClientFactory(sys.argv[1], proxy=proxy)
    factory.protocol = EchoClientProtocol
    connectWS(factory)

    reactor.run()
Пример #25
0
    def onConnect(self, response):
        print("Server connected: {0}".format(response.peer))

    @inlineCallbacks
    def onOpen(self):
        print("WebSocket connection open.")

        # start sending messages every second ..
        while True:
            self.sendMessage(u"1".encode('utf8'))
            yield sleep(5)

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

    def onClose(self, was_clean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))


if __name__ == '__main__':
    log.startLogging(sys.stdout)

    factory = WebSocketClientFactory("ws://localhost:9000/add", debug=False)
    factory.protocol = MyClientProtocol

    reactor.connectTCP("127.0.0.1", 9000, factory)
    reactor.run()
Пример #26
0
    fh = logging.FileHandler(args.filename)
    fh.setLevel(level)
    ch = logging.StreamHandler()
    ch.setLevel(level)
    formatter = logging.Formatter(
        '%(asctime)s-%(name)s:-%(levelname)s: %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    logger.addHandler(fh)
    logger.addHandler(ch)

    #factory=WebSocketClientFactory( 'ws://162.243.154.223:8888/v1/websocket/feed_id=53dde5e6a52633d704000003&format=json&isFront=False',
    #factory=WebSocketClientFactory( 'ws://192.168.1.37:9000/v1/websocket/?feed_id=53dde5e6a52633d704000003&format=json&isFront=False',
    factory = WebSocketClientFactory(
        'ws://{}:{}/v1/websocket/?feed_id=53dde5e6a52633d704000003&format=json&isFront=False'
        .format(args.ip, args.port),
        debug=args.loglevel,
        debugCodePaths=False)
    factory.protocol = EchoClientProtocol

    #factoryVideo=WebSocketClientFactory('ws://162.243.154.223:8888/v1/websocket/feed_id=53dde5e6a52633d704000003&format=video&isFront=False',
    #factoryVideo=WebSocketClientFactory('ws://192.168.1.37:9000/v1/websocket/?feed_id=53dde5e6a52633d704000003&format=video&isFront=False',
    factoryVideo = WebSocketClientFactory(
        'ws://{}:{}/v1/websocket/?feed_id=53dde5e6a52633d704000003&format=video&isFront=False'
        .format(args.ip, args.port),
        debug=args.loglevel,
        debugCodePaths=False)
    factoryVideo.protocol = EchoClientVideoProtocol
    # connectWS(factory)
    connectWS(factoryVideo)
    reactor.run()
    def onMessage(self, payload, isBinary):
        print "onMessage() receive video from robot at: %s " % str(
            time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

    def onClose(self, wasClean, code, reason):
        self.sendClose()


if __name__ == '__main__':

    debug = True

    #factory=WebSocketClientFactory('ws://162.243.154.223:8888/v1/websocket/feed_id=53dde5e6a52633d704000003&format=json&isFront=True',
    #factory=WebSocketClientFactory('ws://192.168.1.37:9000/v1/websocket/?feed_id=53dde5e6a52633d704000003&format=json&isFront=True',
    factory = WebSocketClientFactory(
        'ws://143.89.46.81:9090/v1/websocket/?feed_id=53dde5e6a52633d704000003&format=json&isFront=True',
        debug=debug,
        debugCodePaths=debug)
    factory.protocol = EchoClientProtocol

    #factoryVideo=WebSocketClientFactory('ws://162.243.154.223:8888/v1/websocket/feed_id=53dde5e6a52633d704000003&format=video&isFront=True',
    #factoryVideo=WebSocketClientFactory('ws://192.168.1.37:9000/v1/websocket/?feed_id=53dde5e6a52633d704000003&format=video&isFront=True',
    factoryVideo = WebSocketClientFactory(
        'ws://143.89.46.81:9090/v1/websocket/?feed_id=53dde5e6a52633d704000003&format=video&isFront=True',
        debug=debug,
        debugCodePaths=debug)
    factoryVideo.protocol = EchoClientVideoProtocol
    connectWS(factory)
    #connectWS(factoryVideo)
    reactor.run()
Пример #28
0
        if i:
            self.answer = sys.stdin.readline().strip()
        else:
            logger.info('Answering time out')
        buzzing_lock.release()
        msg = {
            'type': MSG_TYPE_BUZZING_ANSWER,
            'text': self.answer,
            'qid': self.qid,
            'position': self.position
        }
        self.sendMessage(json.dumps(msg).encode('utf-8'))


class KeyPoller(threading.Thread):
    def run(self):
        global buzzed
        while True:
            with buzzing_lock:
                ch = sys.stdin.read(1)
                if ch == 'b':
                    buzzed.set()
            time.sleep(0.1)


if __name__ == '__main__':
    KeyPoller().start()
    factory = WebSocketClientFactory(u"ws://127.0.0.1:9000")
    factory.protocol = KeyboardProtocol
    connectWS(factory)
    reactor.run()
Пример #29
0
      hello()

   def onMessage(self, payload, isBinary):
      if isBinary:
         print("Binary message received: {0} bytes".format(len(payload)))
         print(payload.decode())
      else:
         # printing the size of the encoded image which is received
         print("Encoded size of the received text: {0} bytes".format(len(payload)))
         print(payload.decode())
         

   def onClose(self, wasClean, code, reason):
      print("WebSocket connection closed: {0}".format(reason))



if __name__ == '__main__':

   import sys

   from twisted.python import log
   from twisted.internet import reactor

   log.startLogging(sys.stdout)

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = MyClientProtocol

   reactor.connectTCP("127.0.0.1", 9000, factory)
   reactor.run()
Пример #30
0
def main():
    parser = argparse.ArgumentParser(
        description="Process blinktrade withdrawals requests")

    parser.add_argument('-c',
                        "--config",
                        action="store",
                        dest="config",
                        help='Configuration file',
                        type=str)

    arguments = parser.parse_args()

    candidates = [
        os.path.join(site_config_dir('blinktrade'),
                     'blinktrade_withdrawer.ini'),
        os.path.expanduser('~/.blinktrade/blinktrade_withdrawer.ini')
    ]
    if arguments.config:
        candidates.append(arguments.config)

    config = ConfigParser.SafeConfigParser()
    config.read(candidates)

    if config.has_section('blockchain_info'):
        blockchain_main_password = getpass.getpass(
            'Blockchain.info main password: '******'Blockchain.info second password: '******'blinktrade password: '******'blinktrade second factor authentication: ')

    blinktrade_port = 443
    should_connect_on_ssl = True
    blinktrade_url = urlparse(config.get("blinktrade", "webscoket_url"))
    if blinktrade_url.port is None and blinktrade_url.scheme == 'ws':
        should_connect_on_ssl = False
        blinktrade_port = 80

    db_engine = config.get("database", "sqlalchemy_engine") + ':///' +\
                os.path.expanduser(config.get("database", "sqlalchemy_connection_string"))
    engine = create_engine(db_engine,
                           echo=config.getboolean('database',
                                                  'sqlalchmey_verbose'))
    Base.metadata.create_all(engine)

    factory = WebSocketClientFactory(blinktrade_url.geturl())
    factory.db_session = scoped_session(sessionmaker(bind=engine))
    factory.verbose = config.getboolean("blinktrade", "verbose")
    factory.blinktrade_user = config.get("blinktrade", "user")
    factory.blinktrade_broker_id = config.get("blinktrade", "broker_id")
    factory.currencies = json.loads(config.get("blinktrade", "currencies"))
    factory.methods = json.loads(config.get("blinktrade", "methods"))
    factory.blinktrade_password = blinktrade_password
    factory.blinktrade_2fa = blinktrade_2fa

    factory.blocked_accounts = json.loads(
        config.get("blinktrade", "blocked_accounts"))

    if config.has_section('blockchain_info'):
        from blockchain_info import BlockchainInfoWithdrawalProtocol
        factory.blockchain_guid = config.get("blockchain_info", "guid")
        factory.from_address = config.get("blockchain_info", "from_address")
        factory.note = config.get("blockchain_info", "note")
        factory.blockchain_main_password = blockchain_main_password
        factory.blockchain_second_password = blockchain_second_password
        factory.protocol = BlockchainInfoWithdrawalProtocol

    if config.has_section('mailer'):
        from mailer_protocol import MailerWithdrawalProtocol
        factory.mandrill_apikey = config.get("mailer", "mandrill_apikey")
        factory.mandrill_template_name = config.get("mailer", "template_name")
        factory.mandrill_from_email = config.get("mailer", "from_email")
        factory.mandrill_from_name = config.get("mailer", "from_name")
        factory.mandrill_to_email = config.get("mailer", "to_email")
        factory.mandrill_to_name = config.get("mailer", "to_name")
        factory.mandrill_website = config.get("mailer", "website")
        factory.protocol = MailerWithdrawalProtocol

    if should_connect_on_ssl:
        reactor.connectSSL(blinktrade_url.netloc, blinktrade_port, factory,
                           ssl.ClientContextFactory())
    else:
        reactor.connectTCP(blinktrade_url.netloc, blinktrade_port, factory)

    reactor.run()