def __init__(self, url, debug = False, ident = None): WebSocketClientFactory.__init__(self, url, useragent = ident, debug = debug, debugCodePaths = debug) self.setProtocolOptions(failByDrop = False) # spec conformance ## enable permessage-XXX compression extensions ## offers = [PerMessageDeflateOffer()] #offers = [PerMessageSnappyOffer(), PerMessageBzip2Offer(), PerMessageDeflateOffer()] self.setProtocolOptions(perMessageCompressionOffers = offers) def accept(response): if isinstance(response, PerMessageDeflateResponse): return PerMessageDeflateResponseAccept(response) elif isinstance(response, PerMessageBzip2Response): return PerMessageBzip2ResponseAccept(response) elif isinstance(response, PerMessageSnappyResponse): return PerMessageSnappyResponseAccept(response) self.setProtocolOptions(perMessageCompressionAccept = accept) self.endCaseId = None self.currentCaseId = 0 self.updateReports = True if ident is not None: self.agent = ident else: self.agent = "AutobahnPython/%s" % autobahn.version self.resource = "/getCaseCount"
def create_client_frame(b64patch, **kwargs): """ Kind-of hack-y; maybe better to re-factor the Protocol to have a frame-encoder method-call? Anyway, makes a throwaway protocol encode a frame for us, collects the .sendData call and returns the data that would have gone out. Accepts all the kwargs that WebSocketClientProtocol.sendFrame() accepts. """ # only real way to inject a "known" secret-key for the headers # to line up... :/ b64patch.return_value = b'QIatSt9QkZPyS4QQfdufO8TgkL0=' factory = WebSocketClientFactory(protocols=['wamp.2.json']) factory.protocol = WebSocketClientProtocol factory.doStart() proto = factory.buildProtocol(IPv4Address('TCP', '127.0.0.9', 65534)) proto.transport = MagicMock() proto.connectionMade() proto.data = mock_handshake_server proto.processHandshake() data = [] def collect(d, *args): data.append(d) proto.sendData = collect proto.sendFrame(**kwargs) return b''.join(data)
def run(self): while self.__url is None: discoverySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) discoverySocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True) discoverySocket.settimeout(5) discoverySocket.sendto(b"hello", ("<broadcast>", 8701)) try: data, address = discoverySocket.recvfrom(1024) self.__url = "ws://" + address[0] + ":8702" print ("Found: "+ self.__url) except socket.timeout: print ("No server found") discoverySocket.close() factory = WebSocketClientFactory(self.__url, debug=False) #factory = WebSocketClientFactory("ws://192.168.1.7:8702", debug=False) factory.protocol = BotWebSocketClientProtocol parsed = urlparse(self.__url) ipaddr = parsed.netloc.replace("ws://","").split(':', 1)[0] print ("Connecting to: "+ipaddr+"-"+str(parsed.port)) reactor.connectTCP(ipaddr, parsed.port, factory) reactor.run()
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 #command_library.request_active_xtsm() try: connectWS(factory) command_library.factory = factory command_library.multicast = multicast factory.command_library = command_library print "........................WS Server Running......................." except twisted.internet.error.CannotListenError: print "Can't listen" #server_shutdown() global tcp tcp = PXI_Emulator_TCP() reactor.run()
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
def __init__(self, path, debug, debugCodePaths=False): WebSocketClientFactory.__init__(self, path, debug=debug, debugCodePaths=False) try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) except: log.msg("Error creating raw socket", logLevel=logging.WARN)
def __init__(self, config): self.wsAddress = config.get('coinbase', 'webSocket') self.product = config.get('coinbase', 'product') factory = WebSocketClientFactory(self.wsAddress) factory.protocol = CoinbaseWebSocketClient factory.product = self.product factory.feedHandler = None self.factory = factory
def __init__(self, url): WebSocketClientFactory.__init__(self, url) self.protocolInstance = None self.tickGap = 5 self.tickSetup() self.connect()
def main(): log.startLogging(sys.stdout) factory = WebSocketClientFactory("ws://localhost:9000/add", debug=False) factory.protocol = LeaderBoardLoadGeneratorClient reactor.connectTCP("127.0.0.1", 9000, factory) reactor.run()
def _makeService(self): """ Construct a service for the endpoint as described. """ factory = WebSocketClientFactory() factory.protocol = SlackProtocol factory.bot = self.bot return ClientService(self.bot, factory)
def main(): log.startLogging(sys.stdout) factory = WebSocketClientFactory("ws://localhost:9001", debug=False) factory.protocol = MyClientProtocol reactor.connectTCP("127.0.0.1", 9001, factory) reactor.run()
def gen_coinbase_source(): ret = CoinbaseSource() factory = WebSocketClientFactory("wss://ws-feed.exchange.coinbase.com") factory.queue = ret.queue factory.close_cb = reactor.stop factory.protocol = ExchangeProtocol connectWS(factory) Thread(target=reactor.run, args=(False,)).start() return ret
def setup_websocket(self): try: factory = WebSocketClientFactory("wss://ws-feed.exchange.coinbase.com") ClientProtocol.handler = self.handler factory.protocol = ClientProtocol connectWS(factory) reactor.run() except KeyboardInterrupt: factory.close() self.handler.close_client()
def __init__(self, audioFd, summary, contentType, model, url=None, headers=None, debug=None): self.listeners = [] WebSocketClientFactory.__init__(self, url=url, headers=headers, debug=debug) self.audioFd = audioFd self.summary = summary self.contentType = contentType self.model = model self.openHandshakeTimeout = 6 self.closeHandshakeTimeout = 6
def __init__(self, receiver, url, debug=True): """Constructor Args: receiver: The instance of IARIEventReceiver that will receive updates url: The URL to connect the WebSocket to debug: Optional. Enable greater debugging in WebSocketClientFactory. Defaults to True. """ WebSocketClientFactory.__init__(self, url, debug=debug, protocols=['ari']) self.receiver = receiver
def _connect_client(reactor, api_auth_token, ws_url): factory = WebSocketClientFactory( url=ws_url, headers={ "Authorization": "{} {}".format(SCHEME, api_auth_token), } ) factory.protocol = _StreamingLogClientProtocol factory.on_open = Deferred() endpoint = _url_to_endpoint(reactor, ws_url) return endpoint.connect(factory)
class TestClient(unittest.TestCase): def setUp(self): self.factory = WebSocketClientFactory(protocols=['wamp.2.json']) self.factory.protocol = WebSocketClientProtocol self.factory.doStart() self.proto = self.factory.buildProtocol(IPv4Address('TCP', '127.0.0.1', 65534)) self.transport = MagicMock() self.proto.transport = self.transport self.proto.connectionMade() def tearDown(self): self.factory.doStop() # not really necessary, but ... del self.factory del self.proto def test_unclean_timeout_client(self): """ make a delayed call to drop the connection (client-side) """ if False: self.proto.debug = True self.proto.factory._log = print # get to STATE_OPEN self.proto.websocket_key = b64decode('6Jid6RgXpH0RVegaNSs/4g==') self.proto.data = mock_handshake_server self.proto.processHandshake() self.assertEqual(self.proto.state, WebSocketServerProtocol.STATE_OPEN) self.assertTrue(self.proto.serverConnectionDropTimeout > 0) with replace_loop(Clock()) as reactor: # now 'do the test' and transition to CLOSING self.proto.sendCloseFrame() self.proto.onCloseFrame(1000, "raw reason") # check we scheduled a call self.assertEqual(len(reactor.calls), 1) self.assertEqual(reactor.calls[0].func, self.proto.onServerConnectionDropTimeout) self.assertEqual(reactor.calls[0].getTime(), self.proto.serverConnectionDropTimeout) # now, advance the clock past the call (and thereby # execute it) reactor.advance(self.proto.closeHandshakeTimeout + 1) # we should have called abortConnection self.assertEqual("call.abortConnection()", str(self.proto.transport.method_calls[-1])) self.assertTrue(self.proto.transport.abortConnection.called) # ...too "internal" for an assert? self.assertEqual(self.proto.state, WebSocketServerProtocol.STATE_CLOSED)
def quote_stream(account, venue, protocol, debug=False): url = 'wss://api.stockfighter.io/ob/api/ws/%(account)s/venues/%(venue)s/tickertape' % locals() log.startLogging(sys.stdout) factory = WebSocketClientFactory(url, debug=debug) factory.protocol = protocol # SSL client context: default ## if factory.isSecure: contextFactory = ssl.ClientContextFactory() else: contextFactory = None connectWS(factory, contextFactory) reactor.run()
def __init__(self, queue, summary, contentType, model, url=None, headers=None, debug=None): WebSocketClientFactory.__init__(self, url=url, headers=headers) self.queue = queue self.summary = summary self.contentType = contentType self.model = model self.queueProto = Queue.Queue() self.openHandshakeTimeout = 10 self.closeHandshakeTimeout = 10 # start the thread that takes care of ending the reactor so the script can finish automatically (without ctrl+c) endingThread = threading.Thread(target=self.endReactor, args= ()) endingThread.daemon = True endingThread.start()
def startDaemon(self): # build urls self.apiUrl = self.buildApiUrl() self.wsUrl = self.buildWebSocketUrl() # get token data = { "login" : self.setApiAuth[0], "password" : self.setApiAuth[1] } url = "{0}/api/auth".format(self.apiUrl) r = self.POST(url, data) self.serverToken = r["token"] factory = WebSocketClientFactory(self.buildWebSocketUrl() + "?token={0}".format(self.serverToken), debug=False) factory.protocol = SmartClientProtocol factory.protocol.sm = self reactor.connectSSL(self.baseHost, 443, factory, ssl.ClientContextFactory())
def __init__(self, threadID, uri, notificationQ): self.threadID = threadID self.uri = uri self.notification_q = notificationQ self.running = True WebSocketClientFactory.__init__(self,'ws://'+str(self.uri[7:])) threading.Thread.__init__(self) self.protocol = MyClientProtocol self.setProtocolOptions(openHandshakeTimeout=15) print self.uri address = self.uri[7:].split('/')[0] path = self.uri[7:].split('/')[1:] ip = address.split(':')[0] port = address.split(':')[1] reactor.connectTCP(ip, int(port), self)
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)
def __init__(self, url: str, app, token: str, secure: bool): """ Connect to the websocket :param url: URL to connect to :param app: Ref back to object that launched the WS :param token: Client token to to WS authentication :pram secure: is the server connection should be secure """ if secure: protocol = "wss" else: protocol = "ws" WebSocketClientFactory.__init__(self, f"{protocol}://{url}", headers={"authorization": token}) self.app = app self.client_protocol = None
def __init__(self, url, num, rate): self.url = url self.num = num self.rate = rate self.factory = WebSocketClientFactory( args.url, debug=False, ) self.factory.protocol = MyClientProtocol
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)
def setUp(self): self.factory = WebSocketClientFactory(protocols=['wamp.2.json']) self.factory.protocol = WebSocketClientProtocol self.factory.doStart() self.proto = self.factory.buildProtocol(IPv4Address('TCP', '127.0.0.1', 65534)) self.transport = MagicMock() self.proto.transport = self.transport self.proto.connectionMade()
def __init__(self): logger.info('Initiating Slack RTM start request') data = api('rtm.start', no_latest=1) # Make the protocol a partial so that we can send the full info from rtm.start self.protocol = partial(Client, data) logger.info('creating WebSocketClientFactory with %s', data['url']) return WebSocketClientFactory.__init__(self, url=data['url'])
def run_client(self): self.factory = WebSocketClientFactory(self.ws_url + '?action=subscribe') self.factory.protocol = MyClientProtocol def handler(record): self.stream.append(record) self.factory.handler = handler connectWS(self.factory)
def _create_websocket(self, queue, access_token, host): headers = {AUTHORIZATION: TOKEN % access_token} self.ws = WebSocketClientFactory(daemo.WEBSOCKET + host + daemo.WS_BOT_SUBSCRIBE_URL, headers=headers) self.ws.protocol = ClientProtocol self.ws.queue = queue connectWS(self.ws) reactor.run()
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)
def __init__(self, app_key): self.app_key = app_key self.events = {} self.channels = {} self.factory = WebSocketClientFactory("wss://ws-ap3.pusher.com/app/%s?client=python-twisted?version=1.0&protocol=4" % app_key) self.factory.protocol = PusherProtocol self.factory.singleton = None self.factory.pusher = self self.on("pusher:ping", self.on_ping) connectWS(self.factory)
def __init__(self, queue, summary, contentType, model, url=None, headers=None, debug=None): WebSocketClientFactory.__init__(self, url=url, headers=headers) self.queue = queue self.summary = summary # self.dirOutput = dirOutput self.contentType = contentType self.model = model self.queueProto = Queue.Queue() self.openHandshakeTimeout = 10 self.closeHandshakeTimeout = 10 # start the thread that takes care of ending the reactor so # the script can finish automatically (without ctrl+c) endingThread = threading.Thread(target=self.endReactor, args=()) endingThread.daemon = True endingThread.start()
def __init__(self, threadID, uri, notificationQ): self.threadID = threadID self.uri = uri self.notification_q = notificationQ self.running = True WebSocketClientFactory.__init__(self, 'ws://' + str(self.uri[7:]), debug=True) threading.Thread.__init__(self) self.protocol = MyClientProtocol self.setProtocolOptions(openHandshakeTimeout=15) print self.uri address = self.uri[7:].split('/')[0] path = self.uri[7:].split('/')[1:] ip = address.split(':')[0] port = address.split(':')[1] reactor.connectTCP(ip, int(port), self)
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()
def __init__(self, url, num, concurrency, rate, messages, spawn): self.url = url self.num = num self.concurrency = concurrency self.rate = rate self.spawn = spawn self.messages = messages self.factory = WebSocketClientFactory(args.url, ) self.factory.protocol = MyClientProtocol self.factory.num_messages = self.messages self.factory.message_rate = self.rate
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)
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)
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
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"
def __init__(self, load_runner, websocket_url, statsd_client, scenario, endpoint=None, endpoint_ssl_cert=None, endpoint_ssl_key=None, *scenario_args, **scenario_kw): logging.debug("Connecting to {}".format(websocket_url)) self._factory = WebSocketClientFactory( websocket_url, headers={"Origin": "http://localhost:9000"}) self._factory.protocol = WSClientProtocol self._factory.harness = self if websocket_url.startswith("wss"): self._factory_context = ssl.ClientContextFactory() else: self._factory_context = None # somewhat bogus encryption headers self._crypto_key = "keyid=p256dh;dh=c2VuZGVy" self._encryption = "keyid=p256dh;salt=XZwpw6o37R-6qoZjw6KwAw" # Processor and Websocket client vars self._scenario = scenario self._scenario_args = scenario_args self._scenario_kw = scenario_kw self._processors = 0 self._ws_clients = {} self._connect_waiters = deque() self._load_runner = load_runner self._stat_client = statsd_client self._vapid = Vapid() if "vapid_private_key" in self._scenario_kw: self._vapid = Vapid( private_key=self._scenario_kw.get("vapid_private_key")) else: self._vapid.generate_keys() self._claims = () if "vapid_claims" in self._scenario_kw: self._claims = self._scenario_kw.get("vapid_claims") self._endpoint = urlparse.urlparse(endpoint) if endpoint else None self._agent = None if endpoint_ssl_cert: self._agent = Agent(reactor, contextFactory=UnverifiedHTTPS( endpoint_ssl_cert, endpoint_ssl_key)) if hasattr(endpoint_ssl_cert, 'seek'): endpoint_ssl_cert.seek(0) if endpoint_ssl_key and hasattr(endpoint_ssl_key, 'seek'): endpoint_ssl_key.seek(0)
def __init__(self, url): self.agent = autobahn.twisted.__ident__ WebSocketClientFactory.__init__(self, url, useragent=self.agent) self.setProtocolOptions(failByDrop=False) # spec conformance # enable permessage-deflate WebSocket protocol extension offers = [PerMessageDeflateOffer()] self.setProtocolOptions(perMessageCompressionOffers=offers) def accept(response): if isinstance(response, PerMessageDeflateResponse): return PerMessageDeflateResponseAccept(response) self.setProtocolOptions(perMessageCompressionAccept=accept) # setup client testee stuff self.endCaseId = None self.currentCaseId = 0 self.updateReports = True self.resource = "/getCaseCount"
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())
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) self._conns[conn_key].disconnect() del (self._conns[conn_key])
def do_test(self): self.client_factory = WebSocketClientFactory("ws://127.0.0.1:" + str(self.wss_port)) self.client_factory.protocol = ClientTProtocol # keep track of the connector object so we can close it manually: 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
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")
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))
def mail_listener(mail_domain='mail.scewpt.com', message_filter_dic=None): #client_factory = WebSocketClientFactory('services://' + mail_domain + ':8080', debug=False) client_factory = WebSocketClientFactory('ws://mail.scewpt.com:8080') print 'mail to unique:', message_filter_dic from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol point = TCP4ClientEndpoint(reactor, mail_domain, 8080) report = WSMailClientProtocol() report.email_deferred = defer.Deferred() report.factory = client_factory d = connectProtocol(point, report) def msg_filter(protocol=None, mf=None): protocol.message_filter = mf d.addCallback(msg_filter, message_filter_dic) return report.email_deferred
def __init__(self, queue, base_model, customization_weight, custom=False, url=None, headers=None, debug=None): WebSocketClientFactory.__init__(self, url=url, headers=headers) self.queue = queue self.base_model = base_model self.customization_weight = customization_weight self.custom = custom self.protocolQueue = Queue.Queue() self.closeHandshakeTimeout = 10 # Expected time for a closing handshake (seconds) self.openHandshakeTimeout = 10 # Defining and starting the thread that ends the script automatically. endingThread = threading.Thread(target=self.endReactor, args=()) endingThread.daemon = True # Functions as a daemon in the background. endingThread.start()
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)
def _connect_tls(self, websocket_location, shared_seed): ws_url = str(websocket_location) factory = WebSocketClientFactory(ws_url) factory.protocol = OutgoingSocket factory.setProtocolOptions(openHandshakeTimeout=30, autoPingInterval=30, autoPingTimeout=5) factory.ms_protocol_layer = self factory.ms_shared_seed = shared_seed options = ssl.optionsForClientTLS(hostname=websocket_location.host) c = connectWS(factory, options) return WebsocketConnectionAttempt(c)
def main(): ret = 0 global gconfig config = None try: config = ConfigParser.ConfigParser() config.read('./eqclient_autobahn.ini') gconfig = config print('success read config.') except: print('error read config. abort. (%s, %s)' % ( sys.exc_info()[0], sys.exc_info()[1])) return 2 try: print('try connect : %s' % (config.get('default', 'API_URL'))) #log.startLogging(sys.stdout) factory = WebSocketClientFactory( config.get('default', 'API_URL'), debug=False) factory.protocol = MyClientProtocol connectWS(factory) reactor.run() except KeyboardInterrupt: ws.close() return 0 except: print("EXCEPT: %s" % sys.exc_info()[1]) return 1 return ret
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
def main(): parser = argparse.ArgumentParser(description="Process all withdrawals using blockchain.info wallet api") parser.add_argument('-b', "--blinktrade_websocket_url", action="store", dest="blintrade_webscoket_url", help='Blinktrade Websocket Url', type=str) parser.add_argument('-u', "--blinktrade_username", action="store", dest="blintrade_user", help='Blinktrade User', type=str) parser.add_argument('-p', "--blinktrade_password", action="store", dest="blintrade_password", help='Blinktrade Password', type=str) parser.add_argument('-db', "--db_engine", action="store", dest="db_engine", help='Database Engine', type=str) parser.add_argument('-v', "--verbose", action="store_true", default=False, dest="verbose", help='Verbose') wallet_mnemonic = getpass.getpass('wallet_mnemonic: ') arguments = parser.parse_args() if not arguments.db_engine: parser.print_help() return blinktrade_port = 443 should_connect_on_ssl = True blinktrade_url = urlparse(arguments.blintrade_webscoket_url) if blinktrade_url.port is None and blinktrade_url.scheme == 'ws': should_connect_on_ssl = False blinktrade_port = 80 db_engine = create_engine(arguments.db_engine, echo=arguments.verbose) Base.metadata.create_all(db_engine) factory = WebSocketClientFactory(blinktrade_url.geturl()) factory.blintrade_user = arguments.blintrade_user factory.blintrade_password = arguments.blintrade_password factory.blockchain_guid = arguments.blockchain_guid factory.wallet_mnemonic = wallet_mnemonic factory.db_session = scoped_session(sessionmaker(bind=db_engine)) factory.verbose = arguments.verbose factory.protocol = BtcWithdrawalProtocol 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()
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()
def main(): parser = argparse.ArgumentParser(description="Validates peoples identity using edentiti (green id) identity provider") parser.add_argument('-b', "--blinktrade_websocket_url", action="store", dest="blintrade_webscoket_url", help='Blinktrade Websocket Url', type=str) parser.add_argument('-u', "--blinktrade_username", action="store", dest="blintrade_user", help='Blinktrade User', type=str) parser.add_argument('-p', "--blinktrade_password", action="store", dest="blintrade_password", help='Blinktrade Password', type=str) parser.add_argument('-c', "--customer_id", action="store", dest="edentiti_customer_id", help='Edentiti Web service password', type=str) parser.add_argument('-P', "--password", action="store", dest="edentiti_password", help='Edentiti Web service password', type=str) parser.add_argument('-v', "--verbose", action="store_true", default=False, dest="verbose", help='Verbose') parser.add_argument('-t', "--test", action="store_true", default=False, dest="test", help='Verbose') test_wsdl = 'https://test.edentiti.com/Registrations-Registrations/VerificationServicesPassword?wsdl' production_wsdl = 'https://www.edentiti.com/Registrations-Registrations/VerificationServicesPassword?wsdl' arguments = parser.parse_args() wsdl = production_wsdl if arguments.test: wsdl = test_wsdl wsdl_client = SoapClient( wsdl=wsdl, soap_ns="soapenv", ns="ns1", trace=True) blinktrade_port = 443 should_connect_on_ssl = True blinktrade_url = urlparse(arguments.blintrade_webscoket_url) if blinktrade_url.port is None and blinktrade_url.scheme == 'ws': should_connect_on_ssl = False blinktrade_port = 80 factory = WebSocketClientFactory(blinktrade_url.geturl()) factory.blintrade_user = arguments.blintrade_user factory.blintrade_password = arguments.blintrade_password factory.wsdl_client = wsdl_client factory.edentiti_customer_id = arguments.edentiti_customer_id factory.edentiti_password = arguments.edentiti_password factory.verbose = arguments.verbose factory.protocol = BtcWithdrawalProtocol 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()
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