Example #1
0
	def connect(self,addr):
		"""connects to target server"""
		if self.client is not None:
			if self.client.did_handshake:
				raise UsageError("Already Connected!")
		try:
			self.factory=P22PClientFactory(self,addr)
			if self.factory.isSecure and (ssl is not None):
				context=ssl.ClientContextFactory()
			else:
				context=None
			#self.reactor.connectTCP(ip,port,self.factory,timeout=10)
			websocket.connectWS(self.factory,context,timeout=10)
			while self.client is None:
				#wait for self.client to be set
				pass
			if self.client is False:
				self.client=None
				raise ConnectionError("Cant connect to Server!")
			while not self.client.did_handshake:
				pass
		except:
			self.factory=None
			self.client=None
			raise
Example #2
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
    #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()
Example #3
0
    def start(klass, address, pdid, realm='paradrop', start_reactor=False,
              debug=False, extra=None, reconnect=True):
        '''
        Creates a new instance of this session and attaches it to the router
        at the given address and realm.

        reconnect: The session will attempt to reconnect on connection failure
            and continue trying indefinitely.
        '''
        # Enable log messages of autobahn for debugging
        #import txaio
        #txaio.start_logging()

        dee = Deferred()

        component_config = ComponentConfig(realm=u''+realm, extra=u''+pdid)
        session_factory = BaseSessionFactory(config=component_config, deferred=dee)
        session_factory.session = klass

        transport_factory = BaseClientFactory(session_factory, url=address)
        if not reconnect:
            transport_factory.maxRetries = 0
        transport_factory.setProtocolOptions(autoPingInterval=8., autoPingTimeout=4.,)
        context_factory = ClientContextFactory()
        websocket.connectWS(transport_factory, context_factory)

        if start_reactor:
            reactor.run()

        return dee
Example #4
0
def StartPiCalcClient(echo_server_url, echo_server_port, picalcname="Raspi", debug=False):
    if debug:
        log.startLogging(sys.stdout)
    headers = {"PiClient": picalcname}
    factory = PiWebSocketFactory(u"ws://{}:{}/ws_pi?pi".format(echo_server_url, echo_server_port),
                                 headers=headers)
    connectWS(factory)
    reactor.run()
Example #5
0
    def connect(self, host, port):
        """
        Make a connection to a server.

        """
        url = 'ws://{0}:{1}/'.format(host, port)
        log.msg('pubsubclub:  Connecting to %s' % url)
        websocket.connectWS(self.factory(url))
Example #6
0
def agarWS(data, game):
    iphost, token = data.split()
    ip, port = iphost.split(':')
    port = int(port)
    factory = AgarClientFactory("ws://%s:%d" % (ip, port), headers={'Origin':'http://agar.io'})
    factory.token = token
    factory.game = game
    connectWS(factory)
Example #7
0
 def connect(self):
     print "WEBSOCKET connecting", self.isSecure
     ## SSL client context: default
     ##
     if self.isSecure:
         contextFactory = ssl.ClientContextFactory()
     else:
         contextFactory = None
     connectWS(self, contextFactory)
Example #8
0
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
Example #9
0
 def connectDc(self, ws):
     self.log.info("the websocket address is %s" % ws)
     from autobahn.twisted.websocket import connectWS
     wsFactory = WsFactory(ws, self)
     self.f = wsFactory
     wsFactory.setProtocolOptions(
             perMessageCompressionOffers=None,
             perMessageCompressionAccept=None)
     connectWS(wsFactory)
Example #10
0
 def remove_client(self, ws_client):
     """Remove a websocket connection from the client registry"""
     processor = self._ws_clients.pop(ws_client, None)
     if not processor:
         # Possible failed connection, if we have waiting processors still
         # then try a new connection
         if len(self._connect_waiters):
             connectWS(self._factory, contextFactory=self._factory_context)
         return
Example #11
0
def speech_to_text_ibm(file_path):
   # add audio files to the processing queue
   q = Queue.Queue()
   q.put((1,file_path))

   hostname = "stream.watsonplatform.net"   
   headers = {}
   
   credentials = ['c224d410-abd8-4783-97a7-02ff3feb6d3c','sVDa2MAL4gQU']
   model = 'en-US_NarrowbandModel'
   contentType = 'audio/wav'
   threads = '10'
   
   # authentication header
   string = credentials[0] + ":" + credentials[1]
   headers["Authorization"] = "Basic " + base64.b64encode(string)

   # create a WS server factory with our protocol
   url = "wss://" + hostname + "/speech-to-text/api/v1/recognize?model=" + model

   summary = {}
   factory = WSInterfaceFactory(q, summary, contentType, model, url, headers, debug=False)
   factory.protocol = WSInterfaceProtocol

   print 'Transcribing...'
   for i in range(min(int(threads),q.qsize())):
      factory.prepareUtterance()

      # SSL client context: default
      if factory.isSecure:
         contextFactory = ssl.ClientContextFactory()
      else:
         contextFactory = None
      connectWS(factory, contextFactory)

   reactor.run()
   return summary[1]['hypothesis']


# Testing response time between services
# from timeit import default_timer as timer
# file_path = './converted/13635218_10209465570533683_1943824153_n.wav'

# start = timer()
# print speech_to_text_offline(file_path)
# end = timer()
# print('Offlines: ', end-start)

# start = timer()
# print speech_to_text_ibm_rest(file_path)
# end = timer()
# print('IBM: ', end-start)

# start = timer()
# print speech_to_text_google(file_path)
# end = timer()
# print('Google: ', end-start)
Example #12
0
    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 __init__(self, app_key):
     self.app_key = app_key
     self.events = {}
     self.channels = {}
     self.factory = WebSocketClientFactory("ws://ws.pusherapp.com:80/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)
Example #14
0
 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()
Example #15
0
   def connect(self):
      self.factory = PlywoodWebSocketClientFactory("ws://0.0.0.0:17998", debug = False, debugWamp = False)
      self.factory.protocol = PlywoodWebSocketClientProtocol
      self.factory.base_client = self

      connectWS(self.factory)

      self.reactor_thread = threading.Thread(target=reactor.run, args=(False,))
      self.reactor_thread.daemon = True
      self.reactor_thread.start()
Example #16
0
    def start(klass, pdid, address=None, realm='crossbardemo', extra=None,
            start_reactor=False, debug=False, retry=True):
        '''
        Creates a new instance of this session and attaches it to the router
        at the given address and realm. The pdid is set manually now since we trust
        clients. Excessively.

        For now the realm is automatically set as a demo realm since we are not
        using multiple realms.

        Optional values that can be passed through extra:
        authid: ID to use for authentication (login or key checking).  This can
            be used when setting pdid to be a subdomain of one's domain.  For
            example, the user "pd.damouse" can connect to the fabric as
            pdid="pd.damouse.aardvark" by supplying his credentials for
            authid="pd.damouse".
        '''
        if not address: 
            address = FABRIC_URL

        # Configuration
        if extra is None:
            extra = {}
        else:
            extra = dict.copy(extra)

        extra['pdid'] = u'' + pdid

        dee = Deferred()

        component_config = ComponentConfig(realm=pdid, extra=extra)
        session_factory = FabricSessionFactory(config=component_config, deferred=dee)
        session_factory.session = klass

        transport_factory = FabricClientFactory(session_factory, debug=debug, debug_wamp=debug)
        
        if not retry:
            transport_factory.maxRetries = 0

        uri = urlparse.urlparse(address)
        transport_factory.host = uri.hostname
        transport_factory.port = uri.port
        transport_factory.isSecure = (uri.scheme == 'wss')

        context_factory = ClientContextFactory()

        websocket.connectWS(transport_factory, context_factory)

        if start_reactor:
            reactor.run()

        return dee
Example #17
0
   def start(self):
      ## the directory watcher
      ##
      self.watcher = DirWatcher(dir = self.directory)

      ## start directory watcher on _background_ thread
      ##
      reactor.callInThread(self.watcher.loop, self.onDirEvent)

      ## start WAMP client (on main reactor thread)
      ##
      self.client = DirWatchClientFactory(self)
      connectWS(self.client)
Example #18
0
    def _connect(self):
        if self.token is None or self.token == '':
            raise LoginError('Invalid token, try using fetch_token first.')

        if self._protocol:
            return defer.succeed(self._protocol)

        d = defer.Deferred()
        self.factory = DiscordClientFactory(self._gateway, token=self.token, deferred=d, reactor=self.reactor)

        websocket.connectWS(self.factory)
        d.addCallback(self.set_protocol)
        return d
def connect(uri):
    """
    Constructs a MessageTestFactory, connects to the desired WebSocket endpoint
    URI, waits for the MessageTestProtocol to be constructed, and then returns
    the protocol instance.
    """
    factory = MessageTestFactory(uri)
    factory.setProtocolOptions(failByDrop=False, openHandshakeTimeout=1)

    ws.connectWS(factory, timeout=1)
    protocol = pytest.blockon(factory.connected)

    pytest.blockon(protocol.opened)
    return protocol
Example #20
0
 def _stream(self):  # pragma: no cover
     """Runs in a sub-process to perform stream consumption"""
     self.factory.protocol = LiveStream
     self.factory.datasift = {
         'on_open': self._on_open,
         'on_close': self._on_close,
         'on_message': self._on_message,
         'send_message': None
     }
     if self.config.ssl:
         from datasift.twisted_ssl import ClientContextFactory
         connectWS(self.factory, contextFactory=ClientContextFactory())
     else:
         connectWS(self.factory)
     reactor.run()
Example #21
0
def StreamPiData(echo_server_url='localhost', echo_server_port=8081, customcallback=None, statsonly=False):
    """
    Connect to the Echo server to stream the digits of pi
    :param echo_server_url: 127.0.0.1
    :param echo_server_port: 9000
    :return:none
    """
    url = "ws://{}:{}/ws_pi?pi".format(echo_server_url, echo_server_port)
    print "connecting to {}".format(url)
    client = ShowPiStreamFactory(url)
    client.protocol.showpi = not statsonly
    connectWS(client)
    client.protocol.customCalback = customcallback

    reactor.run()
 def connectBunch(self):
    if self.currentCnt + self.batchsize < self.targetCnt:
       c = self.batchsize
       redo = True
    else:
       c = self.targetCnt - self.currentCnt
       redo = False
    for i in xrange(0, c):
       factory = MassConnectFactory(self.uri)
       factory.test = self
       factory.retrydelay = self.retrydelay
       connectWS(factory)
       self.currentCnt += 1
    if redo:
       reactor.callLater(float(self.batchdelay)/1000., self.connectBunch)
Example #23
0
    def RegisterWampClient():

        ## start logging to console
        # log.startLogging(sys.stdout)

        # create a WAMP application session factory
        component_config = types.ComponentConfig(
            realm = realm,
            extra = {"ID":ID})
        session_factory = wamp.ApplicationSessionFactory(
            config = component_config)
        session_factory.session = WampSession

        # create a WAMP-over-WebSocket transport client factory
        transport_factory = WampWebSocketClientFactory(
            session_factory,
            url = url,
            serializers = [MsgPackSerializer()],
            debug = False,
            debug_wamp = False)

        # start the client from a Twisted endpoint
        conn = connectWS(transport_factory)
        confnodesroot.logger.write(_("WAMP connecting to URL : %s\n")%url)
        return conn
Example #24
0
def RegisterWampClient(wampconf):

    WSClientConf = LoadWampClientConf(wampconf)

    ## start logging to console
    # log.startLogging(sys.stdout)

    # create a WAMP application session factory
    component_config = types.ComponentConfig(
        realm = WSClientConf["realm"],
        extra = {"ID":WSClientConf["ID"]})
    session_factory = wamp.ApplicationSessionFactory(
        config = component_config)
    session_factory.session = WampSession

    # create a WAMP-over-WebSocket transport client factory
    transport_factory = ReconnectingWampWebSocketClientFactory(
        session_factory,
        url = WSClientConf["url"],
        serializers = [MsgPackSerializer()],
        debug = False,
        debug_wamp = False)

    # start the client from a Twisted endpoint
    conn = connectWS(transport_factory)
    print "WAMP client connecting to :",WSClientConf["url"]
    return conn
Example #25
0
    def connect(self):
        """Connect the client factory to the WebSocket server

        Returns:
        An instance of twisted.internet.interfaces.IConnector
        """
        return connectWS(self)
Example #26
0
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()
Example #27
0
 def _connectClient(self, connected, opened, clientDisconnected):
     factory = WampClientFactory('ws://localhost:9000', debugWamp=True)
     factory.protocol = ClientProtocol
     factory.onConnectionMade = connected
     factory.onSessionOpen = opened
     factory.onConnectionLost = clientDisconnected
     self.factory = factory
     return connectWS(factory)
Example #28
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)
Example #29
0
    def run(self):
        """ run the server up if foreground or background mode """
        server_url = "wss://%s:%d/ws" % (conf.HOST, conf.PORT)
        log.msg("Server>", server_url)
        transport = ComponentFactory(self.factory, server_url, debug=conf.DEBUG, debugCodePaths=conf.DEBUG)
        transport.setProtocolOptions(acceptMaskedServerFrames=True)
        websocket.connectWS(transport)

        if not self.isBackground:
            reactor.run()
            exit(0)
        #
        #   In background mode we return here and twistd picks up the slack
        #
        application = service.Application(conf.APP_NAME)
        logfile = DailyLogFile(conf.LOGFILE, conf.LOGPATH)
        application.setComponent(ILogObserver, FileLogObserver(logfile).emit)
        return application
Example #30
0
def operate_conn(serverAddr,pipe=None):
	'''
		operate the conmunicate with server 
	'''
	globals()['PIPE'] = pipe # change the global variable PIPE

	print 'pipe is ',pipe
	if pipe : 
		print 'monitor start'
		monitor = Thread(target = handlerMessage)
		monitor.daemon = True
		monitor.start()

	facotry = MyWebSocketClientFactory(serverAddr)
	facotry.protocol = ProbeWebsocketClientProtocol
	connectWS(facotry)
	arpUpdate()
	reactor.run()