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"
Exemple #2
0
    def __init__(self, receiver, host, apps, userpass, port=DEFAULT_PORT,
                 timeout_secs=60, subscribe_all=False):
        """Constructor

        :param receiver The object that will receive events from the protocol
        :param host: Hostname of Asterisk.
        :param apps: App names to subscribe to.
        :param port: Port of Asterisk web server.
        :param timeout_secs: Maximum time to try to connect to Asterisk.
        :param subscribe_all: If true, subscribe to all events.
        """
        url = "ws://%s:%d/ari/events?%s" % \
              (host, port,
               urllib.urlencode({'app': apps, 'api_key': '%s:%s' % userpass}))
        if subscribe_all:
            url += '&subscribeAll=true'
        LOGGER.info("WebSocketClientFactory(url=%s)", url)
        try:
            WebSocketClientFactory.__init__(self, url, debug=True,
                                            protocols=['ari'], debugCodePaths=True)
        except TypeError:
            WebSocketClientFactory.__init__(self, url, protocols=['ari'])
        self.timeout_secs = timeout_secs
        self.attempts = 0
        self.start = None
        self.receiver = receiver
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
Exemple #4
0
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()
Exemple #5
0
 def __init__(self, api_key, use_ssl=True, debug=False, **kwargs):
     self.debug = debug
     client_name = 'twistedPusher'
     client_version = '0.1'
     proto = use_ssl and 'wss' or 'ws'
     port = use_ssl and 443 or 80
     url = '%s://ws.pusherapp.com:%s/app/%s?client=%s&version=%s&protocol=6&flash=false' % (proto, port, api_key, client_name, client_version)
     WebSocketClientFactory.__init__(self, url=url, **kwargs)
    def __init__(self, url):
        WebSocketClientFactory.__init__(self, url)

        self.protocolInstance = None
        self.tickGap = 5
        self.tickSetup()

        self.connect()
def playout_reload_schedule(host, port):
    print ("Connecting to ws://%s:%s" % (host, port))
    factory = WebSocketClientFactory("ws://%s:%s" % (host, port))
    factory.protocol = SendCommandProtocol
    point = TCP4ClientEndpoint(reactor, host, port)
    d = point.connect(factory)
    d.addErrback(failed)
    return d
   def __init__(self, debug):
      WebSocketClientFactory.__init__(self, debug = debug)

      self.endCaseId = None
      self.currentCaseId = 0

      self.updateReports = True
      self.agent = "AutobahnClient/%s" % autobahn.version
      self.path = "/getCaseCount"
   def __init__(self, url, debug, debugCodePaths):
      WebSocketClientFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths)

      self.endCaseId = None
      self.currentCaseId = 0

      self.updateReports = True
      self.agent = "AutobahnClient/%s" % autobahn.version
      self.resource = "/getCaseCount"
Exemple #10
0
   def __init__(self, debug):
      WebSocketClientFactory.__init__(self, debug = debug)

      self.endCaseId = None
      self.currentCaseId = 0

      self.updateReports = True
      self.agent = "AutobahnClient/%s" % pkg_resources.get_distribution("autobahn").version
      self.path = "/getCaseCount"
   def __init__(self, url, debug = False):
      WebSocketClientFactory.__init__(self, url, debug = debug, debugCodePaths = debug)
      self.setProtocolOptions(failByDrop = False) # spec conformance

      self.endCaseId = None
      self.currentCaseId = 0

      self.updateReports = True
      self.agent = "AutobahnClient/%s" % autobahn.version
      self.resource = "/getCaseCount"
Exemple #12
0
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()
Exemple #13
0
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()
Exemple #14
0
    def __init__(self, url, debug, debugCodePaths):
        WebSocketClientFactory.__init__(self,
                                        url,
                                        debug=debug,
                                        debugCodePaths=debugCodePaths)

        self.endCaseId = None
        self.currentCaseId = 0

        self.updateReports = True
        self.agent = "AutobahnClient/%s" % autobahn.version
        self.resource = "/getCaseCount"
Exemple #15
0
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)
Exemple #16
0
    def __init__(self, url, conn):
        """ Initialize the factory.

            @param url:         URL of the Robot process.
            @type  url:         str

            @param conn:        Connection instance which provides callback
                                functions.
            @type  conn:        rce.comm.client.RCE
        """
        WebSocketClientFactory.__init__(self, url)
        self._connection = conn
Exemple #17
0
    def __init__(self, url, conn):
        """ Initialize the factory.

            @param url:         URL of the Robot process.
            @type  url:         str

            @param conn:        Connection instance which provides callback
                                functions.
            @type  conn:        rce.comm.client.RCE
        """
        WebSocketClientFactory.__init__(self, url)
        self._connection = conn
Exemple #18
0
 def __init__(self, url, connection):
     """ Initialize the factory.
         
         @param url:             URL of the Robot Manager.
         @type  url:             str
         
         @param connection:      Connection instance which provides callback
                                 functions.
         @type  connection:      pyrce.connection._Connection
     """
     WebSocketClientFactory.__init__(self, url)
     self._connection = connection
Exemple #19
0
    def setUp(self):
        self._server = Server()
        port = self._server.start()

        address = "ws://localhost:%d" % port

        factory = WebSocketClientFactory(address)
        factory.protocol = Protocol
        factory.setProtocolOptions(openHandshakeTimeout=0)

        self._connector = connectWS(factory)

        self._client_factory = factory
    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()
Exemple #21
0
 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)
Exemple #22
0
    def __init__(self, url, debug=False, serializers=None, reactor=None):

        if serializers is None:
            serializers = [WampMsgPackSerializer(), WampJsonSerializer()]

        self._serializers = {}
        for ser in serializers:
            self._serializers[ser.SERIALIZER_ID] = ser

        protocols = ["wamp.2.%s" % ser.SERIALIZER_ID for ser in serializers]

        WebSocketClientFactory.__init__(self,
                                        url,
                                        debug=debug,
                                        protocols=protocols,
                                        reactor=reactor)
 def buildProtocol(self, addr):
     log.msg("Connected to realtime server at %s." % addr.host)
     
     # reset exponentially-increasing delay
     self.resetDelay()
     
     # build protocol as usual
     return WebSocketClientFactory.buildProtocol(self, addr)
Exemple #24
0
   def __init__(self,
                url,
                debug = False,
                serializers = None,
                reactor = None):

      if serializers is None:
         serializers = [WampMsgPackSerializer(), WampJsonSerializer()]

      self._serializers = {}
      for ser in serializers:
         self._serializers[ser.SERIALIZER_ID] = ser

      protocols = ["wamp.2.%s" % ser.SERIALIZER_ID for ser in serializers]

      WebSocketClientFactory.__init__(self,
                                      url,
                                      debug = debug,
                                      protocols = protocols,
                                      reactor = reactor)
   def __init__(self, spec, debug = False):

      WebSocketClientFactory.__init__(self, debug = debug, debugCodePaths = debug)
      FuzzingFactory.__init__(self, spec.get("outdir", "./reports/servers/"))

      # needed for wire log / stats
      self.logOctets = True
      self.logFrames = True

      self.spec = spec
      self.specCases = parseSpecCases(self.spec)
      self.specExcludeAgentCases = parseExcludeAgentCases(self.spec)
      print "Autobahn WebSockets %s/%s Fuzzing Client" % (autobahntestsuite.version, autobahn.version)
      print "Ok, will run %d test cases against %d servers" % (len(self.specCases), len(spec["servers"]))
      print "Cases = %s" % str(self.specCases)
      print "Servers = %s" % str([x["url"] + "@" + x["agent"] for x in spec["servers"]])

      self.currServer = -1
      if self.nextServer():
         if self.nextCase():
            connectWS(self)
Exemple #26
0
    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)
Exemple #27
0
def main():
    parser = create_parser()
    args = parser.parse_args()
    if args.debug or not args.logfile:
        print 'debug logging to console'
        log.addObserver(log.FileLogObserver(sys.stdout).emit)
    if isinstance(args.logfile, basestring):
        log_file = open(args.logfile, 'a')
        print 'logging to ' + str(log_file)
        log.startLogging(log_file)
    ws_factory = WebSocketClientFactory(args.websocket)
    ws_factory.protocol = RecordClientProtocol
    connectWS(ws_factory)

    wsgi_resource = WSGIResource(reactor, reactor.getThreadPool(), app)
    site = Site(wsgi_resource)
    web_service = internet.TCPServer(5000, site)
    application = service.Application('BarnTown')
    web_service.setServiceParent(application)
    reactor.listenTCP(5000, site)
    reactor.run()
Exemple #28
0
    def __init__(self, server, port, account, character, ticket, **kwargs):
        self.account = unicode(account)
        self.character = unicode(character)
        self.ticket = unicode(ticket)

        self.caching = kwargs.get('caching', True)
        self.on_close = kwargs.get('connection_lost', lambda: None)
        self.on_open = kwargs.get('connection_open', lambda: None)

        self.callbacks = {}
        self.handlers = []
        self.client = None
        self.pinger = None

        class WebsocketClient(WebSocketClientProtocol):
            def onOpen(cl_self):
                logger.debug("Ready to introduce ourselves.!")
                self.client = cl_self
                self._introduce()
                self.pinger = task.LoopingCall(lambda: cl_self.sendMessage(opcode.PING))
                self.pinger.start(45, False)
                self.on_open()

            def connectionLost(cl_self, reason):
                logger.debug("Connection closed with reason {reason}".format(reason=reason))
                self.client = None
                if self.pinger:
                    self.pinger.stop()
                self.on_close()
                WebSocketClientProtocol.connectionLost(cl_self, reason)

            def onMessage(cl_self, message, binary):
                if self.pinger:
                    self.pinger.stop()
                    self.pinger.start(45, False)
                self.on_message(cl_self, message)

        factory = WebSocketClientFactory("ws://{server}:{port}".format(server=server, port=port), debug=False)
        factory.protocol = WebsocketClient
        self.factory = factory
Exemple #29
0
def main(argv):

    try:
        opts, args = getopt.getopt(argv, 'hw:o:',
                                   ['help', 'ws=', 'operation='])

    except getopt.GetoptError:
        usage()

    ws = 'ws://localhost:9000'
    op = 'p'

    for opt, val in opts:
        if opt in ('-h', '--help'):
            usage()
        elif opt in ('-o', '--operation'):
            op = val
        elif opt in ('-w', '--ws'):
            ws = val

    factory = WebSocketClientFactory(ws, debug=True)
    factory.protocol = CountClientProtocol
    connectWS(factory)
    reactor.run()
Exemple #30
0
    def __init__(self, key, secret, currency, http_api, coin='BTC', **kwargs):
        WebSocketClientFactory.__init__(self, **kwargs)

        self.evt = common.Event(eventprefix="//mtgox")
        self.key = binascii.unhexlify(key.replace('-', ''))
        self.secret = base64.b64decode(secret)
        self.currency = currency
        self.http_api = http_api
        self.coin = coin

        self.known_channels = {
                'ticker': 'd5f06780-30a8-4a48-a2f8-7ed181b4a13f',
                'depth':  '24e67e0d-1cad-4cc0-9e7a-f8523ef460fe',
                'trade':  'dbf1dee9-4f2e-4a08-8cb7-748919a71b21',
                'lag':    '85174711-be64-4de1-b783-0628995d7914'}

        self.client = None
        self.connected = False

        self.evt.listen('idkey', self.got_idkey)
        self.evt.listen('remark', self.got_remark)
        self.evt.listen('channel', self.got_channel)

        self.idkey_refresh_task = task.LoopingCall(self.refresh_idkey)
Exemple #31
0
import sys
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, \
                               WebSocketClientProtocol, \
                               connectWS


class EchoClientProtocol(WebSocketClientProtocol):
    def sendHello(self):
        self.sendMessage("Hello, world!")

    def onOpen(self):
        self.sendHello()

    def onMessage(self, msg, binary):
        print "Got echo: " + msg
        reactor.callLater(1, self.sendHello)


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 = EchoClientProtocol
    connectWS(factory)

    reactor.run()
Exemple #32
0
    def on_centrifuge_message(self, msg):
        global COUNT
        COUNT += 1
        if COUNT == NUM_CLIENTS*NUM_CLIENTS:
            stop = time.time()
            print stop - self.start
            reactor.stop()


def generate_token(secret_key, project_id, user_id):
    sign = hmac.new(six.b(str(secret_key)))
    sign.update(six.b(user_id))
    sign.update(six.b(str(project_id)))
    token = sign.hexdigest()
    return token


if __name__ == '__main__':

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

    factory = WebSocketClientFactory(URL)
    factory.protocol = ThroughputClientProtocol

    for i in range(NUM_CLIENTS):
        connectWS(factory)

    reactor.run()
Exemple #33
0
 def create_socket(self):
     num = random.random()
     try:
         r = requests.get("http://" + LOX_ADDR + "/jdev/sys/getkey?" + str(num))
         pass
     except Exception, e:
         print "LOX_DEVICE::auth key request failed"
         raise
     else:
         if r.status_code == 200:
             protocol = (
                 hmac.new(r.json()["LL"]["value"].decode("hex"), LOX_USER + ":" + LOX_PASS, digestmod=hashlib.sha1)
                 .digest()
                 .encode("hex")
             )
             factory = WebSocketClientFactory("ws://" + LOX_ADDR + "/ws/", protocols=[protocol], debug=True)
             factory.protocol = self.proxy
             connectWS(factory)
             self.isClosed = False
         else:
             print "LOX_DEVICE::Failed to Handshake with loxone:HTTP_STATUS_CODE:" + r.status_code
             return
         self.initialized = True
         while not self.isClosed:
             print random.choice(["(>'.')>", "<('.'<)", ":)", ":(", "XD", "oo", "||", "u"])
             gevent.sleep(1)  # don't block event loop
         gevent.sleep(1)
         print "End: create_socket"
         # Put Reconnect code here???
     finally:
         pass
Exemple #34
0
                               WebSocketClientProtocol, \
                               connectWS


class EchoClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello, world!")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)


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])
   # uncomment to use Hixie-76 protocol
   factory.setProtocolOptions(allowHixie76 = True, version = 0)
   factory.protocol = EchoClientProtocol
   connectWS(factory)

   reactor.run()
Exemple #35
0
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      if msg == self.msg:
        print("It works!")
      else:
        print("Wrong message!")
      
      reactor.stop()

if __name__ == "__main__":
   if len(sys.argv) < 2:
      print "Need the WebSocket server address, i.e. ws://localhost:8081/echo/websocket"
      sys.exit(1)

   debug = False
   if debug:
      log.startLogging(sys.stdout)

   print "Using Twisted reactor class %s" % str(reactor.__class__)

   url = sys.argv[1]

   factory = WebSocketClientFactory(url, debug = debug, debugCodePaths = debug)
   factory.setProtocolOptions(version = 13)
   factory.protocol = EchoClientProtocol
   connectWS(factory)

   reactor.run()
Exemple #36
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)
Exemple #37
0
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, \
                               WebSocketClientProtocol, \
                               connectWS


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):
        print "Send auth"
        self.sendMessage('{"action":"auth","key":"foo"}')
        #reactor.callLater(2, self.sendHello)

    def onOpen(self):
        self.sendHello()

    def onMessage(self, msg, binary):
        print "onMessage - Send read"
        self.sendMessage('{"action":"read","id":"all"}')


if __name__ == '__main__':
    #factory = WebSocketClientFactory("ws://localhost:8082")
    factory = WebSocketClientFactory("ws://127.0.0.1:8082")
    factory.protocol = BroadcastClientProtocol
    connectWS(factory)

    reactor.run()
Exemple #38
0
##  distributed under the License is distributed on an "AS IS" BASIS,
##  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
##  See the License for the specific language governing permissions and
##  limitations under the License.
##
###############################################################################

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class EchoClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello, world!")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = EchoClientProtocol
   connectWS(factory)
   reactor.run()
Exemple #39
0
class FrameBasedHashClientProtocol(WebSocketClientProtocol):
    """
   Message-based WebSockets client that generates stream of random octets
   sent to WebSockets server as a sequence of frames all in one message.
   The server will respond to us with the SHA-256 computed over frames.
   When we receive response, we repeat by sending a new frame.
   """
    def sendOneFrame(self):
        data = randomByteString(FRAME_SIZE)
        self.sendMessageFrame(data)

    def onOpen(self):
        self.count = 0
        self.beginMessage(opcode=WebSocketProtocol.MESSAGE_TYPE_BINARY)
        self.sendOneFrame()

    def onMessage(self, message, binary):
        print "Digest for frame %d computed by server: %s" % (self.count,
                                                              message)
        self.count += 1
        self.sendOneFrame()


if __name__ == '__main__':

    factory = WebSocketClientFactory()
    factory.protocol = FrameBasedHashClientProtocol
    reactor.connectTCP("localhost", 9000, factory)
    reactor.run()
 def __init__(self, url, debug = False):
    WebSocketClientFactory.__init__(self, url, debug = debug, debugCodePaths = debug)
Exemple #41
0
class FrameBasedHashClientProtocol(WebSocketClientProtocol):
    """
   Message-based WebSockets client that generates stream of random octets
   sent to WebSockets server as a sequence of frames all in one message.
   The server will respond to us with the SHA-256 computed over frames.
   When we receive response, we repeat by sending a new frame.
   """
    def sendOneFrame(self):
        data = randomByteString(FRAME_SIZE)
        self.sendMessageFrame(data)

    def onOpen(self):
        self.count = 0
        self.beginMessage(opcode=WebSocketProtocol.MESSAGE_TYPE_BINARY)
        self.sendOneFrame()

    def onMessage(self, message, binary):
        print "Digest for frame %d computed by server: %s" % (self.count,
                                                              message)
        self.count += 1
        self.sendOneFrame()


if __name__ == '__main__':

    factory = WebSocketClientFactory("ws://localhost:9000")
    factory.protocol = FrameBasedHashClientProtocol
    connectWS(factory)
    reactor.run()
Exemple #42
0
##  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
##  See the License for the specific language governing permissions and
##  limitations under the License.
##
###############################################################################

import random
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class BroadcastClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello from Python!")
      reactor.callLater(random.random()*5, self.sendHello)

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got message: " + msg


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = BroadcastClientProtocol
   connectWS(factory)
   reactor.run()
Exemple #43
0
    def __init__(self, url, reactor, deferred, **kw):
        WebSocketClientFactory.__init__(self, url, **kw)

        self._reactor = reactor
        self._deferred = deferred
Exemple #44
0
        if self.count < FRAME_COUNT:
            self.sendOneFrame()
        elif not self.finished:
            self.endMessage()
            self.finished = True

        if self.count >= FRAME_COUNT:
            self.sendClose()

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


if __name__ == '__main__':

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

    enableCompression = True
    if enableCompression:
        from autobahn.compress import PerMessageDeflateOffer, \
                                      PerMessageDeflateResponse, \
                                      PerMessageDeflateResponseAccept

        ## 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):
Exemple #45
0
import os
import time
from random import shuffle
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class FSClient(WebSocketClientProtocol):

    # event on new connection with client 
    def onOpen(self):
        self.sendMessage(OPERATION)

    # get response from fileserver
    def onMessage(self, msg, binary):
        print "%s" % msg
        reactor.stop()
    
    
if __name__ == '__main__':
    import sys
    if len(sys.argv)<3:
        sys.exit("Using fsclient.py [PORT] [COMMAND]")
    PORT = int(sys.argv[1])
    OPERATION = sys.argv[2]
    factory = WebSocketClientFactory("ws://" + ADDRESS + ":" + str(PORT), debug = False)
    factory.protocol = FSClient
    connectWS(factory)
    reactor.run()
    
Exemple #46
0
 def connectGephi(self):
     wsClientFactory = WebSocketClientFactory(GEPHI_SERVER_URL)
     wsClientFactory.protocol = GephiClientProtocol
     wsClientFactory.broker = self
     connectWS(wsClientFactory)
Exemple #47
0
def generate_message(message, message_text):
  response = {
    "action": "publish_message",
    "data": {
      "channel": message["channel"],
      "message": message_text,
    },
  }
  return response

def generate_signature(secret, method, path, body, params, exclude_params=["signature"]):
  body = "" if body is None else body
  signature = secret + method.upper() + path + prepare_query_string(params, exclude_params) + body
  return urlsafe_b64encode(hashlib.sha256(signature).digest())[:43]

def prepare_query_string(params, exclude_params):
  params = [(key, value) for key, value in params.iteritems() if key not in exclude_params]
  params.sort(key=lambda x: x[0])
  return "".join("%s=%s" % (key, value) for key, value in params)


if __name__ == '__main__':
  expires = int(time.time()) + 300
  params = { "api_key": API_KEY, "expires": str(expires) }
  params["signature"] = generate_signature(SECRET, "GET", "/eventhub", "", params)
  query_string = "&".join(key + "=" + value for key, value in params.iteritems())
  factory = WebSocketClientFactory("ws://localhost:5000/eventhub?{0}".format(query_string))
  factory.protocol = WebSocketHandler
  connectWS(factory)
  reactor.run()
Exemple #48
0
 def __init__(self, url):
     WebSocketClientFactory.__init__(self, url)
##  Unless required by applicable law or agreed to in writing, software
##  distributed under the License is distributed on an "AS IS" BASIS,
##  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
##  See the License for the specific language governing permissions and
##  limitations under the License.
##
###############################################################################

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol


class EchoClientProtocol(WebSocketClientProtocol):
    def sendHello(self):
        self.sendMessage("Hello, world!")

    def onOpen(self):
        self.sendHello()

    def onMessage(self, msg, binary):
        print "Got echo: " + msg
        reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

    factory = WebSocketClientFactory()
    factory.protocol = EchoClientProtocol
    reactor.connectTCP("localhost", 9000, factory)
    reactor.run()
Exemple #50
0
        self.seen = set()


    def onMessage(self, msg, binary):
        if binary:
            log.warning('Binary message ignored {!r}'.format(msg))
            return
        jd = json.loads(msg)
        jd['data'] = json.loads(jd['data'])
        if jd['action'].startswith('1-questions-active'):
            qid = do_something(jd)
            if qid not in self.seen:
                self.sendMessage('1-question-{}'.format(qid))
		try:
                qinfo = Site('stackoverflow').questions(qid).filter('withbody')[0]._data                
	            qinfo['_id'] = qid
        	    qinfo['datetime_seen'] = datetime.now()
                posts.insert(qinfo)
                self.seen.add(qid)
		except Exception:
			pass
        else:
            do_something_else(jd)


if __name__ == '__main__':
    factory = WebSocketClientFactory("ws://sockets.ny.stackexchange.com", debug=False)
    factory.protocol = QuestionFeedProtocol
    connectWS(factory)
    reactor.run()
Exemple #51
0
        self.sendMessage("Hello, world!")

    def onOpen(self):
        self.sendHello()

    def onMessage(self, msg, binary):
        print "Got echo: " + msg
        reactor.callLater(1, self.sendHello)

    def onClose(self, wasClean, code, reason):
        print "Connection closed."
        print "wasClean", wasClean
        print "code", code
        print "reason", reason
        reactor.stop()


if __name__ == '__main__':

    debug = True
    log.startLogging(sys.stdout)

    factory = WebSocketClientFactory("ws://127.0.0.1:9000/wsecho",
                                     origin="example.com",
                                     protocols=["foo", "bar"],
                                     debug=debug)
    factory.protocol = EchoClientProtocol
    connectWS(factory)

    reactor.run()
Exemple #52
0
   """
    def sendOneBatch(self):
        data = randomByteString(BATCH_SIZE)

        # Note, that this could complete the frame, when the frame length is reached.
        # Since the frame length here is 2^63, we don't bother, since it'll take
        # _very_ long to reach that.
        self.sendMessageFrameData(data)

    def onOpen(self):
        self.count = 0
        self.beginMessage(opcode=WebSocketProtocol.MESSAGE_TYPE_BINARY)
        self.beginMessageFrame(
            0x7FFFFFFFFFFFFFFF
        )  # 2^63 - This is the maximum imposed by the WS protocol
        self.sendOneBatch()

    def onMessage(self, message, binary):
        print "Digest for batch %d computed by server: %s" % (self.count,
                                                              message)
        self.count += 1
        self.sendOneBatch()


if __name__ == '__main__':

    factory = WebSocketClientFactory("ws://localhost:9000")
    factory.protocol = StreamingHashClientProtocol
    connectWS(factory)
    reactor.run()
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, \
                               WebSocketClientProtocol, \
                               connectWS
 
 
class EchoClientProtocol(WebSocketClientProtocol):
 
   def sendHello(self):
      self.sendMessage("Hello, world!")
 
   def onOpen(self):
      self.sendHello()
 
   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)
 
 
if __name__ == '__main__':
 
   factory = WebSocketClientFactory("ws://mozart.kawigi.com:9000", debug = False)
   factory.protocol = EchoClientProtocol
   connectWS(factory)
   reactor.run()

class MessageBasedHashClientProtocol(WebSocketClientProtocol):
    """
   Message-based WebSockets client that generates stream of random octets
   sent to WebSockets server as a sequence of messages. The server will
   respond to us with the SHA-256 computed over each message. When
   we receive response, we repeat by sending a new message.
   """
    def sendOneMessage(self):
        data = randomByteString(MESSAGE_SIZE)
        self.sendMessage(data, binary=True)

    def onOpen(self):
        self.count = 0
        self.sendOneMessage()

    def onMessage(self, message, binary):
        print "Digest for message %d computed by server: %s" % (self.count,
                                                                message)
        self.count += 1
        self.sendOneMessage()


if __name__ == '__main__':

    factory = WebSocketClientFactory()
    factory.protocol = MessageBasedHashClientProtocol
    reactor.connectTCP("localhost", 9000, factory)
    reactor.run()
      pass


class StreamingProducerHashClientProtocol(WebSocketClientProtocol):
   """
   Streaming WebSockets client that generates stream of random octets
   sent to streaming WebSockets server, which computes a running SHA-256,
   which it will send every BATCH_SIZE octets back to us. This example
   uses a Twisted producer to produce the byte stream as fast as the
   receiver can consume, but not faster. Therefor, we don't need the
   application-level flow control as with the other examples.
   """

   def onOpen(self):
      self.count = 0
      producer = RandomByteStreamProducer(self)
      self.registerProducer(producer, True)
      producer.resumeProducing()

   def onMessage(self, message, binary):
      print "Digest for batch %d computed by server: %s" % (self.count, message)
      self.count += 1


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = StreamingProducerHashClientProtocol
   connectWS(factory)
   reactor.run()
Exemple #56
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class EchoClientProtocol(WebSocketClientProtocol):
    def sendHello(self):
        self.sendMessage("Hello, world!")

    def onOpen(self):
        self.sendHello()

    def onMessage(self, msg, binary):
        print "Got echo: " + msg
        reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

    factory = WebSocketClientFactory('ws://localhost:9000', debug=True)
    factory.protocol = EchoClientProtocol
    connectWS(factory)
    reactor.run()
Exemple #57
0
    def onOpen(self):
        self.sendHello()

    def onMessage(self, msg, binary):
        print "Got echo: " + msg
        reactor.callLater(1, self.sendHello)


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)

    # uncomment to use Hixie-76 protocol
    #factory.setProtocolOptions(allowHixie76 = True, version = 0)
    factory.protocol = EchoClientProtocol
    connectWS(factory)

    reactor.run()
Exemple #58
0

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()