def run(self): self._factories = [] for i in xrange(self.config.clients): factory = LoadLatencySubscriberFactory(self.config) connectWS(factory) self._factories.append(factory) publisherFactory = LoadLatencyPublisherFactory(self.config) connectWS(publisherFactory) def printstats(): publishedCnt = publisherFactory.publishedCnt receivedCnt = sum([x.receivedCnt for x in self._factories]) receivedSumRtts = 1000. * sum([sum(x.receivedRtts) for x in self._factories]) if receivedCnt: rttAvg = float(receivedSumRtts) / float(receivedCnt) else: rttAvg = 0 publisherFactory.publishedCnt = 0 for f in self._factories: f.receivedCnt = 0 f.receivedRtts = [] self.publishedCntTotal += publishedCnt self.receivedCntTotal += receivedCnt print "%d, %d, %d, %d, %f" % (publishedCnt, receivedCnt, self.publishedCntTotal, self.receivedCntTotal, rttAvg) reactor.callLater(1, printstats) print "Messages:" print "sent_last, recv_last, sent_total, recv_total, rtt" printstats()
def init_batch(self): print "BATCH STARTED" self.numReceived = 0 self.numReceivedPerClient = {} if app.iteration == 0: # Don't reset data on failed connections between iterations # In the future this could be configurable via a flag self.connectionsLost = [] self.connectionsFailed = [] # Either "ACTIVE" or "DONE" self.state = "ACTIVE" self.startTime = datetime.now() self.check_batchTask = task.LoopingCall(self.check_batch) self.check_batchTask.start(1.0) self.lastResortCall = reactor.callLater(ARGS.max_runtime, self.terminate_batch) self.errors = {} if app.iteration == 0: self.senders = [] for i in xrange(ARGS.num_senders): sender = SenderClientFactory(self, clientId=i) connectWS(sender, timeout=ARGS.websocket_timeout) self.senders.append(sender) else: # Reuse senders between iterations (except for those that failed) for sender in self.senders: if sender.protocol: sender.protocol.publish_bundle()
def main(): parser = create_parser() args = parser.parse_args() if args.debug or (not args.logfile and not args.db): print 'debug logging to console' log.addObserver(log.FileLogObserver(sys.stdout).emit) if not args.logfile and args.db: con = sqlite3.connect(args.db) try: # checking if db exists con.execute('select count(*) from revisions') except sqlite3.OperationalError: print 'creating db ' + args.db create_db(args.db) con = sqlite3.connect(args.db) print 'logging to ' + args.db log.addObserver(partial(db_observer, connection=con)) if isinstance(args.logfile, basestring): log_file = open(args.logfile, 'a') print 'logging to ' + str(log_file) log.startLogging(log_file) factory = WebSocketClientFactory(args.websocket) factory.protocol = RecordClientProtocol connectWS(factory) reactor.run()
def test_server(wsuri, wsuri2 = None): dealer = Dealer() if wsuri2 is None: calculator = Calculator() dealer.register("http://myapp.com/", calculator) broker = Broker() class MyPubSubServerProtocol(WampServerProtocol): def onSessionOpen(self): self.setBroker(broker) self.setDealer(dealer) wampFactory = WampServerFactory(wsuri) wampFactory.protocol = MyPubSubServerProtocol listenWS(wampFactory) if wsuri2: class MyPubSubClientProtocol(WampClientProtocol): def onSessionOpen(self): self.setBroker(broker) self.setDealer(dealer) factory = WampClientFactory(wsuri2) factory.protocol = MyPubSubClientProtocol connectWS(factory)
def connect(cls, uri, debug=False): global client_factory client_factory = ClientFactory(uri) client_factory.uri = uri client_factory.protocol = cls connectWS(client_factory) return client_factory
def main(argv=None): """Main routine of script""" if argv is None: argv = sys.argv try: # parse options and args opts, args = getopt.getopt(argv[1:], "", ["help","node=","capability="]) print "Node/Capability WebSocket consumer." for k,v in opts: if k == "--help": print "A simple python script for consuming readings for a specific Node/Capability pair.\nHit CTRL-C to stop script at any time.\nMust provide all of the parameters listed bellow :" print "\t --node={node's URN}, define the node." print "\t --capability={zone's ID}, define the node's zone." elif k == "--node": node = v elif k == "--capability": capability = v if(not( vars().has_key("node") and vars().has_key("capability"))): print >>sys.stderr, "You must specify --node and --capability" return -1 # initialize WebSocketClientFactory object and make connection PROTOCOL = [''.join([str(node),'@',str(capability)])] factory = WebSocketClientFactory(WS_URL,None,PROTOCOL) factory.protocol = NodeCapabilityConsumerProtocol factory.setProtocolOptions(13) connectWS(factory) reactor.run() except getopt.error, msg: print >>sys.stderr, msg print >>sys.stderr, "for help use -h or --help" return -1
def clientConnectionFailed(self, connector, reason): print "Connection to %s failed (%s)" % (self.spec["servers"][self.currServer]["url"], reason.getErrorMessage()) if self.nextServer(): if self.nextCase(): connectWS(self) else: self.createReports() reactor.stop()
def buildProtocol(self, addr): proto = ReveilleClientFactory.buildProtocol(self, addr) factory = proto.factory_class(self, #"ws://192.168.1.2:9876/reveille", "ws://127.0.0.1:9876/reveille", #debug=debug, #debugCodePaths=debug, ) connectWS(factory)
def test_client(wsuri, dopub): dorpc = False class MyPubSubClientProtocol(WampClientProtocol): def onSessionOpen(self): print "Connected!" def onMyEvent1(topic, event): print "Received event", topic, event d = self.subscribe("http://example.com/myEvent1", onMyEvent1) def subscribeSuccess(subscriptionid): print "Subscribe Success", subscriptionid def subscribeError(error): print "Subscribe Error", error d.addCallbacks(subscribeSuccess, subscribeError) self.counter = 0 def sendMyEvent1(): self.counter += 1 self.publish("http://example.com/myEvent1", { "msg": "Hello from Python!", "counter": self.counter } ) reactor.callLater(2, sendMyEvent1) if dopub: sendMyEvent1() if dorpc: def writeln(res): print res d = self.call("http://myapp.com/add", 23, 7) d.addBoth(writeln) d = self.call("http://myapp2.com/add", 40, 2) d.addBoth(writeln) def onClose(self, wasClean, code, reason): print "Connection closed", reason reactor.stop() factory = WampClientFactory(wsuri) factory.protocol = MyPubSubClientProtocol connectWS(factory)
def __init__(self, host=host, save_data=None, loop_time=LOOP_TIME, reactor=reactor): if save_data is None: save_data=self.save_data factory = ClientFactory(host, save_data) factory.protocol = KinectClient connectWS(factory) self.reactor=reactor self.data = [{'RightHand':{"X":0, "Y":0}, 'RightShoulder':{"X":0, "Y":0}}] self.kk = None self.kin_parameter = None
def start_tracker(data_source_id, args): twilio_client = twilio.Twilio(args.sid, args.token) tracker = DucksboardTracker( data_source_id, twilio_client, args.sid, args.from_, args.to) factory = DucksboardWebSocketClientFactory( args.api_key, tracker, 'wss://api.ducksboard.com/websocket') factory.protocol = DucksboardNotificationProtocol connectWS(factory)
def main(reactor, passes, ip): measurement = Measurement(passes) d = Deferred() d.addCallback(measurement.run) factory = ConnectionFactory('ws://{0}:9000'.format(ip), reactor, d) connectWS(factory) reactor.run()
def clientConnectionLost(self, connector, reason): if self.nextCase(): connector.connect() else: if self.nextServer(): if self.nextCase(): connectWS(self) else: self.createReports() reactor.stop()
def run_admin_command(options): """ Monitor a Crossbar.io server. """ from choosereactor import install_reactor reactor = install_reactor(options.reactor, options.verbose) factory = CrossbarCLIFactory(options, reactor) connectWS(factory) reactor.run()
def sendMessage(self, msg, binary): global thismsg global thisbinary thismsg = msg thisbinary = binary logging.debug("Sending WS message...") self.factory = WebSocketClientFactory("ws://%s:%s" % (self.host, str(self.port)) ) self.factory.protocol = EchoClientProtocol connectWS(self.factory)
def start_comm(self): """Starts the communication using websockets""" from autobahn.websocket import connectWS, WebSocketClientFactory, WebSocketClientProtocol from KinectPlanes.modules.comm import ClientFactory, ClientProtocol self.main_window.btn_connect.setEnabled(False) self.comm_factory = ClientFactory(self.main_window.edit_add.toPlainText(), self) self.comm_factory.protocol = ClientProtocol #self.comm_factory.protocol.set_app(self) connectWS(self.comm_factory)
def main(serial_port, xbmc_uri, xbmc_un, xbmc_pw, saged_uri=None, toilet_ga=None): print "main(%r, %r, %r, %r, %r, %r)" % (serial_port, xbmc_uri, xbmc_un, xbmc_pw, saged_uri, toilet_ga) if not isinstance(serial_port, CPower1200): s = CPower1200(serial_port) s.send_window( dict(x=0, y=0, h=8, w=32), # window 0: top left: time dict(x=32, y=0, h=8, w=32), # window 1: top right: date dict(x=0, y=8, h=8, w=64), # window 2: bottom: nowplaying ) s.send_clock( 0, calendar=CALENDAR_GREGORIAN, multiline=False, display_year=False, display_hour=False, display_minute=False, display_second=False, ) s.send_clock( 1, calendar=CALENDAR_GREGORIAN, multiline=False, display_year=False, display_month=False, display_day=False, display_second=False, ) else: s = serial_port if saged_uri != None: factory = WebSocketClientFactory(saged_uri, debug=True) factory.protocol = SagedClientProtocol factory.protocol.toilet_ga = toilet_ga # unicode(toilet_ga) factory.protocol.sign = s # factory.setProtocolOptions(allowHixie76=True) # reactor.callLater(1, main, s, xbmc_uri, xbmc_un, xbmc_pw) connectWS(factory) # reactor.run() if xbmc_un != None and xbmc_pw != None: auth = (xbmc_un, xbmc_pw) else: auth = None last_playing = False if saged_uri == None: while 1: loop() else: reactor.callInThread(loop, xbmc_uri, auth, s, last_playing, True) reactor.run()
def string_tester_server(): rospy.init_node('stringTesterNode') factory = WebSocketClientFactory("ws://54.216.152.74:9000", debug = False) factory.protocol = TestCenter connectWS(factory) def terminate(): reactor.callFromThread(reactor.stop) rospy.on_shutdown(terminate) reactor.run(installSignalHandlers=False)
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)
def initialize_ws(ignored): #cookie = "session_key=%s; session_id=%s" % \ # (self.session_key, self.session_id) cookie = "session_key=%s; session_id=%s" % \ (self.session_key, self.session_id) factory = KatoWebsocketFactory(KATO_API_WS_URL, self, cookie = cookie, debug = self.debug, debugCodePaths = self.debug, origin = KATO_API_ORIGIN) connectWS(factory) return None
def connect(self, username, password): self.login_auth(username, password) ws = WebSocketClientFactory( self.settings['aps']['ws'][0], useragent='rick astley', debug=True, debugCodePaths=True) SpotifyClientProtocol.sp_settings = self.settings SpotifyClientProtocol.login_callback = self.login_callback ws.protocol = SpotifyClientProtocol connectWS(ws) reactor.run()
def score(self,ip,flag,cookie): try: factory = WebSocketClientFactory("ws://"+ip+":"+str(self.port)+"/stash",debug=True) factory.flag = flag factory.connections = [] factory.observer = self.flagObserver factory.protocol = FlagClientProtocol connectWS(factory) reactor.run() sys.exit(0) except Exception as e: print "exception",e sys.exit(1)
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)
def start(): log.startLogging(sys.stdout) factory = SpiderClientFactory("ws://{}:9000".format(ADMIN_HOST)) factory.protocol = TaskClientProtocol connectWS(factory) def killGroup(): for pid, kw in factory.spiders.iteritems(): try: p = psutil.Process(int(pid)) p.terminate() except Exception, e: print e
def reconnect(self): """Attempt to reconnect the ARI WebSocket. This call will give up after timeout_secs has been exceeded. """ self.attempts += 1 LOGGER.debug("WebSocket attempt #%d", self.attempts) if not self.start: self.start = datetime.datetime.now() runtime = (datetime.datetime.now() - self.start).seconds if runtime >= self.timeout_secs: LOGGER.error(" Giving up after %d seconds", self.timeout_secs) raise Exception("Failed to connect after %d seconds" % self.timeout_secs) connectWS(self)
def _robotConnect(self, resp): """ Internally used method to connect to the Robot manager. """ # Read the response url = resp["url"] current = resp.get("current", None) if current: print("Warning: There is a newer client (version: '{0}') " "available.".format(current)) print("Connect to Robot Manager on: {0}".format(url)) # Make websocket connection to Robot Manager args = urlencode(self._argList + [("key", resp["key"])]) factory = RCERobotFactory("{0}?{1}".format(url, args), self) connectWS(factory)
def main(): if USE_SSL: uri_type = "wss" else: uri_type = "ws" server_url = "%s://%s:%d/rpi/" % (uri_type, SERVER, PORT) if DEBUG: log.startLogging(sys.stdout) factory = ReconnectingWebSocketClientFactory(server_url, useragent = settings.RPI_USER_AGENT, debug = DEBUG) factory.protocol = RPIClientProtocol connectWS(factory) reactor.run()
def _robotConnect(self, resp): """ Internally used method to connect to the Robot process. """ # Read the response url = resp['url'] current = resp.get('current', None) if current: print("Warning: There is a newer client (version: '{0}') " 'available.'.format(current)) print('Connect to Robot Process on: {0}'.format(url)) # Make WebSocket connection to Robot Manager args = urlencode((('userID', self._userID), ('robotID', self._robotID), ('password', self._password))) factory = RCERobotFactory('{0}?{1}'.format(url, args), self) connectWS(factory)
def connect(self, masterUrl, deferred): """ Connect to RCE. @param masterUrl: URL of Authentication Handler of Master Manager @type masterUrl: str @param deferred: Deferred which is called as soon as the connection was successfully established. @type deferred: twisted::Deferred @raise: ConnectionError, if no connection could be established. """ print('Connect to Master Manager on: {0}'.format(masterUrl)) # First make a HTTP request to the Master to get a temporary key argList = [('userID', self._userID), ('robotID', self._robotID)] url = '{0}?{1}'.format(masterUrl, urlencode(argList+[('version', _VERSION)])) try: f = urlopen(url) except HTTPError as e: raise ConnectionError('HTTP Error {0}: {1} - ' '{2}'.format(e.getcode(), e.msg, e.read())) self._connectedDeferred = deferred # Read the response resp = json.loads(f.read()) url = resp['url'] current = resp.get('current', None) if current: print("Warning: There is a newer client (version: '{0}') " 'available.'.format(current)) print('Connect to Robot Manager on: {0}'.format(url)) # Make websocket connection to Robot Manager url = '{0}?{1}'.format(url, urlencode(argList+[('key', resp['key'])])) factory = RCERobotFactory(url, self) connectWS(factory)
def publisher(c_name="all", debug=True): log.startLogging(sys.stdout) if c_name != "all": channel_name = "notifications:%s" % c_name else: channel_name = "notifications:all" #print "user name in Publisher: ", channel_name PUBSUB.subscribe(channel_name) ''' factory = WampClientFactory("ws://%s:9000" % socket.gethostname(), debugWamp=debug) ''' factory = WampClientFactory("ws://localhost:9000", debugWamp=debug) factory.protocol = PubSubClient1 connectWS(factory) reactor.run()
def onOpen(self): self.sendHello() def onMessage(self, msg, binary): print "Got echo: " + msg reactor.callLater(1, self.sendHello) if __name__ == '__main__': log.startLogging(sys.stdout) parser = OptionParser() parser.add_option("-u", "--url", dest = "url", help = "The WebSocket URL", default = "wss://localhost:9000") (options, args) = parser.parse_args() ## create a WS server factory with our protocol ## factory = WebSocketClientFactory(options.url, debug = False) factory.protocol = EchoClientProtocol ## SSL client context: default ## if factory.isSecure: contextFactory = ssl.ClientContextFactory() else: contextFactory = None connectWS(factory, contextFactory) reactor.run()
def getProtocol(self): d = self._get_prot = Deferred() connectWS(self) return d
def connect(self): contextFactory = ssl.ClientContextFactory( ) # necessary for SSL; harmless otherwise connectWS(self, contextFactory)
def run(self): assert (self.factory) assert (self.index) assert (self.params) result = TestResult() finished = Deferred() result.passed = None result.observed = {} result.expected = {} result.log = [] def log(msg, sessionIndex=None, sessionId=None): ts = perf_counter() result.log.append( (ts, sessionIndex, sessionId, msg.encode('utf8'))) return ts result.started = log("Test started.") clients = [] peersready = [] peersgone = [] i = 1 for peerIndex in xrange(self.params.peerCount): ready = Deferred() gone = Deferred() client = self.factory(peerIndex, ready, gone, self, result) clients.append(client) peersready.append(ready) peersgone.append(gone) connectWS(client) i += 1 def shutdown(_): for client in clients: client.proto.sendClose() log("Test client closing ...", client.peerIndex, client.proto.session_id) def launch(_): wait = 2.5 * self._rtt def afterwait(): log("Continuing test ..") d = maybeDeferred(self.test, log, result, clients) d.addCallback(shutdown) def beforewait(): log("Sleeping for <strong>%s ms</strong> ..." % (1000. * wait)) reactor.callLater(wait, afterwait) beforewait() def error(err): ## FIXME print "ERROR", err shutdown() finished.errback(err) def done(res): result.ended = log("Test ended.") for r in res: if not r[0]: log("Client error: %s" % r[1].value) #assert(result.passed is not None) finished.callback(result) DeferredList(peersready).addCallbacks(launch, error) DeferredList(peersgone).addCallbacks(done, error) return finished
def startClient(wsuri, debug=False): factory = BroadcastClientFactory(wsuri, debug) connectWS(factory) return True
class BroadcastClientProtocol(WebSocketClientProtocol): """ Simple client that connects to a WebSocket server, send a HELLO message every 2 seconds and print everything it receives. """ def sendHello(self): self.sendMessage("Hello from Python!") reactor.callLater(2, self.sendHello) def onOpen(self): self.sendHello() def onMessage(self, msg, binary): print "Got message: " + msg if __name__ == '__main__': if len(sys.argv) < 2: print "Need the WebSocket server address, i.e. ws://localhost:9000" sys.exit(1) factory = WebSocketClientFactory(sys.argv[1]) factory.protocol = BroadcastClientProtocol connectWS(factory) reactor.run()
options.parseOptions() except usage.UsageError, errortext: print '%s %s' % (sys.argv[0], errortext) print 'Try %s --help for usage details' % sys.argv[0] sys.exit(1) log.startLogging(sys.stdout) wsuri = options.opts['wsuri'] debug = True if options['debug'] else False padsAsRpcs = True if options['rpc'] else False ## MIDI connector to Launchpad ## launchpadConnector = LaunchpadConnector() launchpadConnector.padsAsRpcs = padsAsRpcs reactor.callInThread(launchpadConnector.run) ## WAMP client factory ## log.msg("Connecting to %s" % wsuri) wampClientFactory = LaunchpadClientFactory(wsuri, debugWamp=debug) wampClientFactory.launchpad = launchpadConnector connectWS(wampClientFactory) webdir = File(".") web = Site(webdir) reactor.listenTCP(8095, web) reactor.run()
def connectGephi(self): wsClientFactory = WebSocketClientFactory(GEPHI_SERVER_URL) wsClientFactory.protocol = GephiClientProtocol wsClientFactory.broker = self connectWS(wsClientFactory)
def start_client(): factory = WebSocketClientFactory('ws://127.0.0.1:9000') # uncomment to use Hixie-76 protocol factory.setProtocolOptions(allowHixie76=True, version=0) factory.protocol = EchoClientProtocol connectWS(factory)
def onSessionOpen(self): print "connected to WAMP server" factory = WebSocketClientFactory(GEPHI_SERVER_URL) factory.protocol = GephiClientProtocol factory.forwarder = self connectWS(factory)