コード例 #1
0
    def main(self, host, port):
        got_request_exception.connect(exception_printer)

        self.stdout.write('Serving at {host}:{port}\n'.format(host = host, port = port))
        application = WSGIHandler()
        server = SocketIOServer((host, port), application, namespace = 'socket.io', policy_server = False)
        server.serve_forever()
コード例 #2
0
ファイル: runsocketio.py プロジェクト: izderadicka/myplaces
def run(addrport, opts):

    if not addrport:
        addr = ''
        port = settings.SIO_PORT
    else:
        m = match(naiveip_re, addrport)
        if m is None:
            raise Exception('"%s" is not a valid port number '
                               'or address:port pair.' % addrport)
        addr, _, _, _, port = m.groups()

    # Make the port available here for the path:
    #   socketio_tags.socketio ->
    #   socketio_scripts.html ->
    #   io.Socket JS constructor
    # allowing the port to be set as the client-side default there.
    os.environ["DJANGO_SOCKETIO_PORT"] = str(port)
    django.setup()
    try:
        bind = (addr, int(port))
        print
        print "SocketIOServer running on %s:%s" % bind
        print
        #inject this setting - needed to initialize zmq in 'green' mode
        settings._wrapped.USE_GEVENT=True
        handler = get_handler(static=opts.use_static_handler)
        server = SocketIOServer(bind, handler, resource="socket.io", policy_server=True)
        server.serve_forever()
    except KeyboardInterrupt:
        pass
コード例 #3
0
    def handle(self, addrport="", *args, **options):
        if not addrport:
            self.addr = ""
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number ' "or address:port pair." % addrport)
            self.addr, _, _, _, self.port = m.groups()

        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        if options.get("use_reloader"):
            start_new_thread(reload_watcher, ())

        try:
            bind = (self.addr, int(self.port))
            print "SocketIOServer running on %s:%s\n\n" % bind
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(bind, handler, resource="socket.io", policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            for key, sock in six.iteritems(server.sockets):
                sock.kill(detach=True)
            server.stop()
            if RELOAD:
                print "Reloading...\n\n"
                restart_with_reloader()
コード例 #4
0
    def handle(self, *args, **options):
        addrport = options["addrport"]
        m = match(naiveip_re, addrport)
        if m is None:
            raise CommandError(
                "%s is not a valid port number or address:port pair." %
                addrport)

        self.addr, _, _, _, self.port = m.groups()

        # Make the port available allowing the port
        # to be set as the client-side default
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        Thread(target=reload_watcher).start()
        try:
            print("\nSocketIOServer running on {addr}:{port}\n".format(
                addr=self.addr, port=self.port))
            handler = self.get_handler(*args, **options)
            bind = (self.addr, int(self.port))
            server = SocketIOServer(bind,
                                    handler,
                                    resource="socket.io",
                                    policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            if RELOAD:
                server.stop()
                print("Reloading...")
                restart_with_reloader()
            else:
                raise
コード例 #5
0
ファイル: server.py プロジェクト: nathancahill/circus
    def run(self, handler):
        try:
            from socketio.server import SocketIOServer
        except ImportError:
            raise ImportError('You need to install gevent_socketio')

        from gevent import monkey
        from gevent_zeromq import monkey_patch
        monkey.patch_all()
        monkey_patch()

        namespace = self.options.get('namespace', 'socket.io')
        policy_server = self.options.get('policy_server', False)

        if self.fd is not None:
            sock = socket.fromfd(self.fd, socket.AF_INET, socket.SOCK_STREAM)
        else:
            sock = (self.host, self.port)

        socket_server = SocketIOServer(sock,
                                       handler,
                                       namespace=namespace,
                                       policy_server=policy_server)
        handler.socket_server = socket_server
        socket_server.serve_forever()
コード例 #6
0
def main():
    try:
        # init
        lModel = RangeManager(int(sys.argv[1]), int(sys.argv[2]))

        monkey.patch_all()
        lApp = Flask(__name__)
        lApp.debug = True
        lApi = Api(lApp)
        FetchRange.sModel = lModel
        Report.sModel = lModel
        Progress.sModel = lModel
        Reset.sModel = lModel
        PushNamespace.sModel = lModel

        # routes
        lApp.add_url_rule('/', 'poll', poll)
        lApp.add_url_rule('/socket.io/<path:path>', 'socket.io', run_socketio)
        lApi.add_resource(FetchRange, '/fetch')
        lApi.add_resource(Report, '/report')
        lApi.add_resource(Progress, '/progress')
        lApi.add_resource(Reset, '/reset')

        # go
        lApp = SharedDataMiddleware(lApp, {})
        lServer = SocketIOServer(('0.0.0.0', 5000),
                                 lApp,
                                 resource="socket.io",
                                 policy_server=False)
        lServer.serve_forever()
    except IndexError:
        print "Usage: " + sys.argv[0] + \
            " <number of ranges> <timeout per range>"
    except KeyboardInterrupt:
        lServer.stop()
コード例 #7
0
def start_server(host_address):
    try:
        server = SocketIOServer(host_address, app, resource='socket.io')
        server.serve_forever()
    except:
        # assume for now server is already running
        pass
コード例 #8
0
    def handle(self, addrport="", *args, **options):

        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        # Make the port available here for the path:
        #   socketio_tags.socketio ->
        #   socketio_scripts.html ->
        #   io.Socket JS constructor
        # allowing the port to be set as the client-side default there.
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        start_new_thread(reload_watcher, ())
        try:
            bind = (self.addr, int(self.port))
            print
            print "SocketIOServer running on %s:%s" % bind
            print
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(bind, handler, resource="socket.io", policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            if RELOAD:
                server.stop()
                print "Reloading..."
                restart_with_reloader()
            else:
                raise
コード例 #9
0
def socketio_server():
    #server = SocketIOServer(('0.0.0.0', 0), SocketApp(), policy_server=False)
    server = SocketIOServer(('0.0.0.0', 38477), SocketApp(), policy_server=False)
    server.start()
    port = server.socket.getsockname()[1]
    print 'http://localhost:'+str(port)+'/'
    server.serve_forever()
コード例 #10
0
ファイル: Web.py プロジェクト: kscottz/SimpleSeer
 def run_gevent_server(self):
     server = SocketIOServer(
         (self.host, self.port),
         self.app, namespace='socket.io',
         policy_server=False)
     log.info('Web server running on %s:%s', self.host, self.port)
     server.serve_forever()
コード例 #11
0
ファイル: server.py プロジェクト: yeahdongcn/weiyu
def cli_server_socketio(
        managed,
        listen=None,
        application=None,
        port=None,
        **kwargs
        ):
    try:
        from socketio.server import SocketIOServer
    except ImportError:
        print(
                'import of socketio.server failed, bailing',
                file=sys.stderr,
                )
        sys.exit(1)

    if not managed and application is None:
        # inspect the caller
        outer_frame = inspect.getouterframes(inspect.currentframe())[2][0]
        app = outer_frame.f_globals['application']
    else:
        app = application

    # Managed (i.e. invoked by 'rain serve') invocations doesn't have the
    # ``listen`` parameter passed in, but have ``port`` set.
    # Just make up one listening on localhost.
    if managed and listen is None:
        listen = ('0.0.0.0', port, )

    server = SocketIOServer(listen, app, **kwargs)
    server.serve_forever()
コード例 #12
0
def socketio_server():
    server = SocketIOServer(
        ('0.0.0.0', port),
        SocketApp(),
        policy_server=False)
    server.start()
    server.serve_forever()
コード例 #13
0
ファイル: runserver_socketio.py プロジェクト: sephii/wwm
    def handle(self, addrport="", *args, **options):

        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        # Make the port available here for the path:
        #   socketio_tags.socketio ->
        #   socketio_scripts.html ->
        #   io.Socket JS constructor
        # allowing the port to be set as the client-side default there.
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        start_new_thread(reload_watcher, ())
        try:
            bind = (self.addr, int(self.port))
            print
            print "SocketIOServer running on %s:%s" % bind
            print
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(bind, handler, resource="socket.io", policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            if RELOAD:
                server.stop()
                print "Reloading..."
                restart_with_reloader()
            else:
                raise
コード例 #14
0
 def spawn_server(func, port):
     print "Serving port", port, func.__name__
     server = SocketIOServer(("localhost", port), func,
                     spawn=greenlet_pool,
                     cors="http://localhost:3000",
                     policy_server=False)
     server.serve_forever()
コード例 #15
0
ファイル: server.py プロジェクト: tomatocurry1/MHacksPublic
def run_dev_server():
    global server
    app.debug = True
    port = 5000
    dapp = DebuggedApplicationFix(app, evalex = True)
    server = SocketIOServer(('' if len(sys.argv) == 1 else sys.argv[1], port), dapp, resource="socket.io")
    server.serve_forever()
コード例 #16
0
ファイル: runserver_socketio.py プロジェクト: johnjsb/zircon
    def start_server(self, addrport="", *args, **options):

        if not addrport:
            self.addr = '127.0.0.1'
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        # Make the port available here for the path:
        # socketio_tags.socketio ->
        # socketio_scripts.html ->
        # io.Socket JS constructor
        # allowing the port to be set as the client-side default there.
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        bind = (self.addr, int(self.port))
        print
        print "SocketIOServer running on http://%s:%s" % bind
        print
        handler = self.get_handler(*args, **options)
        server = SocketIOServer(bind,
                                handler,
                                resource="zircon",
                                policy_server=True)
        server.serve_forever()
コード例 #17
0
ファイル: runserver_socketio.py プロジェクト: hmartiro/zircon
    def start_server(self, addrport="", *args, **options):

        if not addrport:
            self.addr = '127.0.0.1'
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        # Make the port available here for the path:
        # socketio_tags.socketio ->
        # socketio_scripts.html ->
        # io.Socket JS constructor
        # allowing the port to be set as the client-side default there.
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        bind = (self.addr, int(self.port))
        print
        print "SocketIOServer running on http://%s:%s" % bind
        print
        handler = self.get_handler(*args, **options)
        server = SocketIOServer(bind, handler, resource="zircon",
                                policy_server=True)
        server.serve_forever()
コード例 #18
0
ファイル: server.py プロジェクト: weltenwort/madacra-py
 def foo():
     server = SocketIOServer(
             (host, port),
             app,
             namespace="socket.io",
             policy_server=False
             )
     server.serve_forever()
コード例 #19
0
def run_server():
    #app.run('0.0.0.0', 8080, debug=True)
    global app
 
    print 'Starting SocketIO Server with Gevent Mode ...'
    app = SharedDataMiddleware(app, {})
    http_server = SocketIOServer(('', 80), app, namespace="socket.io", policy_server=False)
    http_server.serve_forever()
コード例 #20
0
def main():
    parser = argparse.ArgumentParser(description='Marteau Server')
    parser.add_argument('config', help='Config file', nargs='?')
    parser.add_argument('--version', action='store_true',
                        default=False,
                        help='Displays Marteau version and exits.')
    parser.add_argument('--log-level', dest='loglevel', default='info',
                        choices=LOG_LEVELS.keys() + [key.upper() for key in
                                                     LOG_LEVELS.keys()],
                        help="log level")
    parser.add_argument('--log-output', dest='logoutput', default='-',
                        help="log output")
    parser.add_argument('--host', help='Host', default='0.0.0.0')
    parser.add_argument('--port', help='Port', type=int, default=8080)
    args = parser.parse_args()

    if args.version:
        print(__version__)
        sys.exit(0)

    if args.config is None:
        parser.print_usage()
        sys.exit(0)

    # configure the logger
    configure_logger(logger, args.loglevel, args.logoutput)

    # loading the config file
    config = Config(args.config)

    # loading the app & the queue
    global_config = {}
    if config.has_section('marteau'):
        settings = config.get_map('marteau')
    else:
        settings = {}

    # check is redis is running
    if not redis_available():
        raise IOError('Marteau needs Redis to run.')

    # loading the fixtures plugins
    for fixture in settings.get('fixtures', []):
        import_string(fixture)

    logger.info('Loaded plugins: %s' % ', '.join(get_fixtures()))

    app = webapp(global_config, **settings)
    try:
        httpd = SocketIOServer((args.host, args.port), app,
                               resource="socket.io", policy_server=False)
        logger.info('Hammer ready, at http://%s:%s. Where are the nails ?' %
                    (args.host, args.port))
        httpd.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)
    finally:
        logger.info('Bye!')
コード例 #21
0
ファイル: webresmon.py プロジェクト: izderadicka/webresmon
def main():
    global PORT
    if len(sys.argv)>1:
        PORT=int(sys.argv[1])
    http_server = SocketIOServer(
        ('', PORT),App(), 
        policy_server=False, resource='socket.io'
        )
    # Start the server greenlets
    http_server.serve_forever()
コード例 #22
0
def main():
    global PORT
    if len(sys.argv) > 1:
        PORT = int(sys.argv[1])
    http_server = SocketIOServer(('', PORT),
                                 App(),
                                 policy_server=False,
                                 resource='socket.io')
    # Start the server greenlets
    http_server.serve_forever()
コード例 #23
0
ファイル: rungevent.py プロジェクト: vpineda7/django-realtime
    def main(self, host, port):
        got_request_exception.connect(exception_printer)

        self.stdout.write('Serving at {host}:{port}\n'.format(host=host,
                                                              port=port))
        application = WSGIHandler()
        server = SocketIOServer((host, port),
                                application,
                                namespace='socket.io',
                                policy_server=False)
        server.serve_forever()
コード例 #24
0
ファイル: run.py プロジェクト: dbsr/reloaded
def start_server(host, port, hide_status, debug):
    app.debug = bool(debug)
    app.reloaded['hide_status'] = bool(hide_status)
    server = SocketIOServer((host, int(port)), app, resource='socket.io')
    print "Reloaded server started serving on: {}:{}.".format(host, port)
    try:
        server.serve_forever()
    except socket.error:
        print ("Reloaded server could not bind to port: {}. Is reloaded already"
               " running?".format(port))
        sys.exit(1)
コード例 #25
0
def run_socket_server(addr, port, *args, **options):
    bind = (addr, int(port))
    print
    print "SocketIOServer running on %s:%s" % bind
    print
    handler = get_handler(*args, **options)
    server = SocketIOServer(bind, handler,
                            heartbeat_interval=5,
                            heartbeat_timeout=30,
                            resource="socket.io",
                            policy_server=True)
    server.serve_forever()
コード例 #26
0
ファイル: serve.py プロジェクト: jonnyquan/pyramid_socketio
    def main():
        # Load application and config.
        app = loadapp('config:%s' % cfgfile, relative_to='.')
        server = SocketIOServer((host, port), app,
                                namespace="socket.io")

        try:
            print "Serving on %s:%d (http://127.0.0.1:%d) ..." % (host, port, port)
            server.serve_forever()
        except socket.error, e:
            print "ERROR SERVING WSGI APP: %s" % e
            sys.exit(1)
コード例 #27
0
ファイル: runserver_socketio.py プロジェクト: finid/drawnby
 def handle(self, addrport="", **kwargs):
     if not addrport:
         self.addr = "127.0.0.1"
         self.port = 9000
     else:
         m = match(naiveip_re, addrport)
         if m is None:
             raise CommandError('"%s" is not a valid port number '
                                'or address:port pair.' % addrport)
         self.addr, _, _, _, self.port = m.groups()
     server = SocketIOServer((self.addr, int(self.port)), application)
     server.serve_forever()
コード例 #28
0
def run_socket_server(addr, port, *args, **options):
    bind = (addr, int(port))
    print
    print "SocketIOServer running on %s:%s" % bind
    print
    handler = get_handler(*args, **options)
    server = SocketIOServer(bind,
                            handler,
                            heartbeat_interval=5,
                            heartbeat_timeout=30,
                            resource="socket.io",
                            policy_server=True)
    server.serve_forever()
コード例 #29
0
ファイル: webserver.py プロジェクト: gmvi/CodeDay-Playlist
def run():
    ip_addr = socket.gethostbyname(socket.gethostname())
    print "Listening on %s:%d" % (ip_addr, 5000 if DEBUG else 80)
    log = WriteWrapper(sys.stdout, socketioserver_tf_msg)
    server = SocketIOServer(("", 5000 if DEBUG else 80),
                            app,
                            resource="socket.io",
                            log = log)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        disconnect()
        print " Server Killed"
コード例 #30
0
ファイル: server.py プロジェクト: Forked2/jquery-chat
def main():
    def signal_handler(signal, frame):
        print "Received signal %s scheduling shutdown..." % signal
        server.stop()

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    print 'Listening %s:%s and port 10843 (flash policy)' % (HOST, PORT)
    server = SocketIOServer(
        (HOST, PORT), Application(),
        resource="socket.io", policy_server=True,
        policy_listener=(HOST, 10843))
    server.serve_forever()
コード例 #31
0
ファイル: server.py プロジェクト: al-layth/denigma
def serve_forever(django=False):
    """Starts the gevent-socketio server."""
    logger = getLogger("irc.dispatch")
    logger.setLevel(settings.LOG_LEVEL)
    logger.addHandler(StreamHandler())
    app = IRCApplication(django)
    server = SocketIOServer((settings.HTTP_HOST, settings.HTTP_PORT), app)
    print "%s [%s] listening on %s:%s" % (
        settings.CHAT_VERSION_STRING,
        app.bot.__class__.__name__,
        settings.HTTP_HOST,
        settings.HTTP_PORT,
    )
    server.serve_forever()
コード例 #32
0
ファイル: server.py プロジェクト: McDoku/denigma
def serve_forever(django=False):
    """Starts the gevent-socketio server."""
    logger = getLogger("irc.dispatch")
    logger.setLevel(settings.LOG_LEVEL)
    logger.addHandler(StreamHandler())
    app = IRCApplication(django)
    server = SocketIOServer((settings.HTTP_HOST, settings.HTTP_PORT), app)
    print "%s [%s] listening on %s:%s" % (
        settings.CHAT_VERSION_STRING,
        app.bot.__class__.__name__,
        settings.HTTP_HOST,
        settings.HTTP_PORT,
        )
    server.serve_forever()
コード例 #33
0
ファイル: manager.py プロジェクト: kannibalox/tranny
    def init_webui(self):
        """ Initialize and start the flask based webui. This does not check if it is
        enabled, so that must happen prior to calling this

        :return:
        :rtype:
        """
        host = config.get_default('flask', 'listen_host', 'localhost')
        port = config.get_default('flask', 'listen_port', 5000, int)
        from tranny.app import create_app

        wsgi_app = create_app()
        socketio_app = SocketIOServer((host, port), wsgi_app, resource='socket.io')
        socketio_app.serve_forever()
コード例 #34
0
ファイル: web.py プロジェクト: ricardoard12/ENTS-Pop-Pi
class WebService:
    def __init__(self, bindAddress, port):
        self.__port = port
        self.__bindAddr = bindAddress
        print("Web server starting on " + self.__bindAddr + ":" +
              str(self.__port) + "...")
        self.webThread = threading.Thread(target=self.__start)
        self.webThread.daemon = True
        self.webThread.start()

    def __start(self):
        self.server = SocketIOServer((self.__bindAddr, self.__port),
                                     Application())
        gevent.spawn(self.__onStart)
        self.server.serve_forever()

    def __onStart(self):
        print("Web server started on " + self.__bindAddr + ":" +
              str(self.__port))

    def __broadcast(self, eventName, *args):
        pkt = dict(type="event", name=eventName, args=args, endpoint="/pop")
        for sessid, socket in self.server.sockets.iteritems():
            socket.send_packet(pkt)

    # TODO: These "on" methods should be handled by Observer...
    def onSwipeStart(self):
        self.__broadcast("member-swipe-start")

    def onSwipe(self, credit, cost):
        self.__broadcast("member-swipe", credit, cost)

    def onDeposit(self, cents):
        self.__broadcast("deposit", cents)

    def onPaid(self, newCredit):
        self.__broadcast("paid", newCredit)

    def onNotFound(self):
        self.__broadcast("not-found")

    def onCreditOnly(self):
        self.__broadcast("credit-only")

    def onCreditCompleted(self, newCredit):
        self.__broadcast("credit-completed", newCredit)

    def shutdown(self):
        return  # Nothing to do
コード例 #35
0
ファイル: server.py プロジェクト: xen0n/weiyu
def cli_server_socketio(
        managed,
        listen=None,
        application=None,
        port=None,
        uid=None,
        gid=None,
        **kwargs
        ):
    try:
        from socketio.server import SocketIOServer
    except ImportError:
        print(
                'import of socketio.server failed, bailing',
                file=sys.stderr,
                )
        sys.exit(1)

    if not managed and application is None:
        # inspect the caller
        outer_frame = inspect.getouterframes(inspect.currentframe())[2][0]
        app = outer_frame.f_globals['application']
    else:
        app = application

    # Managed (i.e. invoked by 'rain serve') invocations doesn't have the
    # ``listen`` parameter passed in, but have ``port`` set.
    # Just make up one listening on IPADDR_ANY.
    if managed and listen is None:
        listen = ('0.0.0.0', port, )

    if uid is not None:
        # Do the socket initialization early, then set{g,u}id.
        sock = SocketIOServer.get_listener(
                listen[0],
                kwargs.get('backlog', None),
                None,  # TODO: more sensible default for family
                )

        if gid is not None:
            os.setgid(gid)
        os.setuid(uid)

        # Use the constructed socket.
        server = SocketIOServer(sock, app, **kwargs)
    else:
        server = SocketIOServer(listen, app, **kwargs)

    server.serve_forever()
コード例 #36
0
ファイル: web.py プロジェクト: ricardoard12/ENTS-Pop-Pi
class WebService:
    def __init__(self, bindAddress, port):
        self.__port = port
        self.__bindAddr = bindAddress
        print("Web server starting on " + self.__bindAddr + ":" + str(self.__port) + "...");
        self.webThread = threading.Thread(target=self.__start)
        self.webThread.daemon = True
        self.webThread.start()

    def __start(self):
        self.server = SocketIOServer((self.__bindAddr, self.__port), Application())
        gevent.spawn(self.__onStart)
        self.server.serve_forever()

    def __onStart(self):
        print("Web server started on " + self.__bindAddr + ":" + str(self.__port))

    def __broadcast(self, eventName, *args):
        pkt = dict(type="event",
                   name=eventName,
                   args=args,
                   endpoint="/pop")
        for sessid, socket in self.server.sockets.iteritems():
            socket.send_packet(pkt)

    # TODO: These "on" methods should be handled by Observer...
    def onSwipeStart(self):
        self.__broadcast("member-swipe-start")

    def onSwipe(self, credit, cost):
        self.__broadcast("member-swipe", credit, cost)

    def onDeposit(self, cents):
        self.__broadcast("deposit", cents)

    def onPaid(self, newCredit):
        self.__broadcast("paid", newCredit)

    def onNotFound(self):
        self.__broadcast("not-found")

    def onCreditOnly(self):
        self.__broadcast("credit-only")

    def onCreditCompleted(self, newCredit):
        self.__broadcast("credit-completed", newCredit)

    def shutdown(self):
        return # Nothing to do
コード例 #37
0
def main():
    def signal_handler(signal, frame):
        print "Received signal %s scheduling shutdown..." % signal
        server.stop()

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    print 'Listening %s:%s and port 10843 (flash policy)' % (HOST, PORT)
    server = SocketIOServer((HOST, PORT),
                            Application(),
                            resource="socket.io",
                            policy_server=True,
                            policy_listener=(HOST, 10843))
    server.serve_forever()
コード例 #38
0
ファイル: app.py プロジェクト: pysight/translucent
 def run(self):
     try:
         print 'Listening at %s port %d...' % (self.host, self.port)
         SocketIONamespace.set_app_class(self.app_class)
         if self.debug:
             self.flask_app = SocketIODebugger(self.flask_app,
                 evalex=True, namespace=SocketIONamespace)
         server = SocketIOServer((self.host, self.port), self.flask_app,
             resource='socket.io', policy_server=False)
         if self.debug:
             run_with_reloader(server.serve_forever)
         else:
             server.serve_forever()
     except KeyboardInterrupt:
         print '\rShutting down...'
コード例 #39
0
 def serve_forever(self):
     """Load dbs and run gevent wsgi server"""
     from socketio.server import SocketIOServer
     server = SocketIOServer((self.args.interface, int(self.args.port)),
                             self.application, resource="socket.io",
                             policy_server=False)
     logger.info("Start socket.io server %r:%r",
                 self.args.interface, self.args.port)
     try:
         server.serve_forever()
     except KeyboardInterrupt:
         for socket in server.sockets.values():
             for namespace in socket.active_ns.values():
                 if hasattr(namespace, 'stop_server'):
                     namespace.stop_server()
コード例 #40
0
ファイル: web_socketio.py プロジェクト: suningwz/customaddons
 def serve_forever(self):
     """Load dbs and run gevent wsgi server"""
     from socketio.server import SocketIOServer
     server = SocketIOServer((self.args.interface, int(self.args.port)),
                             self.application,
                             resource="socket.io",
                             policy_server=False)
     logger.info("Start socket.io server %r:%r", self.args.interface,
                 self.args.port)
     try:
         server.serve_forever()
     except KeyboardInterrupt:
         for socket in server.sockets.values():
             for namespace in socket.active_ns.values():
                 if hasattr(namespace, 'stop_server'):
                     namespace.stop_server()
コード例 #41
0
    def handle(self, addrport='', *args, **options):
        """
        Parses all arguments and starts the server. Will reload on
        SIGINT unless the --noreload flag is passed.
        """

        if options.get('enable_coverage'):
            print "Enabling coverage for socketio server."
            coverage_omit = ['*/management/*',
                             '*/migrations/*']

            cov = coverage.coverage(source=['deckr', 'engine'],
                                    omit=coverage_omit,
                                    data_suffix=True,
                                    branch=True)
            cov.start()

        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT

        else:
            address_match = match(naiveip_re, addrport)
            if address_match is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = address_match.groups()

        environ['DJANGO_SOCKETIO_PORT'] = str(self.port)
        if options.get('use_reloader'):
            start_new_thread(reload_watcher, ())

        try:
            bind = (self.addr, int(self.port))
            print 'SocketIOServer running on %s:%s\n\n' % bind
            handler = get_handler(**options)
            server = SocketIOServer(
                bind, handler, resource='socket.io', policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            server.stop()
            if options.get('enable_coverage'):
                cov.stop()
                cov.save()
            if RELOAD:
                print 'Reloading...\n\n'
                restart_with_reloader()
コード例 #42
0
    def handle(self, addrport='', *args, **options):
        """
        Parses all arguments and starts the server. Will reload on
        SIGINT unless the --noreload flag is passed.
        """

        if options.get('enable_coverage'):
            print "Enabling coverage for socketio server."
            coverage_omit = ['*/management/*',
                             '*/migrations/*']

            cov = coverage.coverage(source=['deckr'],
                                    omit=coverage_omit,
                                    data_suffix=True)
            cov.start()

        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT

        else:
            address_match = match(naiveip_re, addrport)
            if address_match is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = address_match.groups()

        environ['DJANGO_SOCKETIO_PORT'] = str(self.port)
        if options.get('use_reloader'):
            start_new_thread(reload_watcher, ())

        try:
            bind = (self.addr, int(self.port))
            print 'SocketIOServer running on %s:%s\n\n' % bind
            handler = get_handler(**options)
            server = SocketIOServer(
                bind, handler, resource='socket.io', policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            server.stop()
            if options.get('enable_coverage'):
                cov.stop()
                cov.save()
            if RELOAD:
                print 'Reloading...\n\n'
                restart_with_reloader()
コード例 #43
0
ファイル: socketioserver.py プロジェクト: Alexlleee/chatbox
def start_socketio():

    def chat(environ, start_response):
        if environ['PATH_INFO'].startswith('/socket.io'):
            return socketio_manage(environ, {'/chat': ChatNamespace})
    dbpath = 'db/database.db'
    if not os.path.exists(os.path.dirname(dbpath)):
        os.makedirs(os.path.dirname(dbpath))
    engine = create_engine("".join(["sqlite:///", dbpath]))
    redisHost = '127.0.0.1'
    redisPort = 6379
    redisConnectionPool = ConnectionPool(host=redisHost, port=int(redisPort))
    dbHandler = DatabaseHandler(engine, redisConnectionPool)
    ChatNamespace.set_db_handler(dbHandler)
    ChatNamespace.cookieName = 'chat_cookie'
    sio_server = SocketIOServer(('', 8080), chat, policy_server=False)
    sio_server.serve_forever()
コード例 #44
0
ファイル: socketioserver.py プロジェクト: Alexlleee/chatbox
def start_socketio():
    def chat(environ, start_response):
        if environ['PATH_INFO'].startswith('/socket.io'):
            return socketio_manage(environ, {'/chat': ChatNamespace})

    dbpath = 'db/database.db'
    if not os.path.exists(os.path.dirname(dbpath)):
        os.makedirs(os.path.dirname(dbpath))
    engine = create_engine("".join(["sqlite:///", dbpath]))
    redisHost = '127.0.0.1'
    redisPort = 6379
    redisConnectionPool = ConnectionPool(host=redisHost, port=int(redisPort))
    dbHandler = DatabaseHandler(engine, redisConnectionPool)
    ChatNamespace.set_db_handler(dbHandler)
    ChatNamespace.cookieName = 'chat_cookie'
    sio_server = SocketIOServer(('', 8080), chat, policy_server=False)
    sio_server.serve_forever()
コード例 #45
0
ファイル: circushttpd.py プロジェクト: themgt/circus
    def run(self, handler):
        try:
            from socketio.server import SocketIOServer
        except ImportError:
            raise ImportError('You need to install gevent_socketio')

        from gevent import monkey
        from gevent_zeromq import monkey_patch
        monkey.patch_all()
        monkey_patch()

        namespace = self.options.get('namespace', 'socket.io')
        policy_server = self.options.get('policy_server', False)
        socket_server = SocketIOServer((self.host, self.port),
                                       handler,
                                       namespace=namespace,
                                       policy_server=policy_server)
        handler.socket_server = socket_server
        socket_server.serve_forever()
コード例 #46
0
    def handle(self, addrport='', *args, **options):
        if not addrport:
            self.addr = ''
            self.port = 8000
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        environ['DJANGO_SOCKETIO_PORT'] = str(self.port)

        if options.get('use_psyco'):
            try:
                from psycogreen.gevent import patch_psycopg
            except ImportError:
                raise CommandError('Could not patch psycopg. '
                                   'Is psycogreen installed?')
            patch_psycopg()

        if options.get('use_reloader'):
            start_new_thread(reload_watcher, ())

        try:
            bind = (self.addr, int(self.port))
            print 'SocketIOServer running on %s:%s\n\n' % bind
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(bind,
                                    handler,
                                    resource='socket.io',
                                    policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            for key, sock in six.iteritems(server.sockets):
                sock.kill(detach=True)
            server.stop()
            if RELOAD:
                print 'Reloading...\n\n'
                restart_with_reloader()
コード例 #47
0
    def run(self, handler):
        try:
            from socketio.server import SocketIOServer
        except ImportError:
            raise ImportError('You need to install gevent_socketio')

        # sets up the ZMQ/Gevent environ
        from circus import _patch   # NOQA

        namespace = self.options.get('namespace', 'socket.io')
        policy_server = self.options.get('policy_server', False)

        if self.fd is not None:
            sock = socket.fromfd(self.fd, socket.AF_INET, socket.SOCK_STREAM)
        else:
            sock = (self.host, self.port)

        socket_server = SocketIOServer(sock, handler,
                                       namespace=namespace,
                                       policy_server=policy_server)
        handler.socket_server = socket_server
        socket_server.serve_forever()
コード例 #48
0
class SocketIO(object):
    def __init__(self, app=None):
        if app:
            self.init_app(app)
        self.messages = {}
        self.rooms = {}
        self.server = None

    def init_app(self, app):
        app.wsgi_app = SocketIOMiddleware(app, self)

    def get_namespaces(self, base_namespace=BaseNamespace):
        class GenericNamespace(base_namespace):
            socketio = self
            base_emit = base_namespace.emit
            base_send = base_namespace.send

            def initialize(self):
                self.rooms = set()

            def process_event(self, packet):
                message = packet['name']
                args = packet['args']
                app = self.request
                return self.socketio._dispatch_message(app, self, message,
                                                       args)

            def join_room(self, room):
                if self.socketio._join_room(self, room):
                    self.rooms.add(room)

            def leave_room(self, room):
                if self.socketio._leave_room(self, room):
                    self.rooms.remove(room)

            def recv_connect(self):
                if self.socketio.server is None:
                    self.socketio.server = self.environ['socketio'].server
                ret = super(GenericNamespace, self).recv_connect()
                app = self.request
                self.socketio._dispatch_message(app, self, 'connect')
                return ret

            def recv_disconnect(self):
                app = self.request
                self.socketio._dispatch_message(app, self, 'disconnect')
                for room in self.rooms.copy():
                    self.leave_room(room)
                return super(GenericNamespace, self).recv_disconnect()

            def recv_message(self, data):
                app = self.request
                return self.socketio._dispatch_message(app, self, 'message',
                                                       [data])

            def recv_json(self, data):
                app = self.request
                return self.socketio._dispatch_message(app, self, 'json',
                                                       [data])

            def emit(self, event, *args, **kwargs):
                ns_name = kwargs.pop('namespace', None)
                broadcast = kwargs.pop('broadcast', False)
                room = kwargs.pop('room', None)
                if broadcast or room:
                    if ns_name is None:
                        ns_name = self.ns_name
                    return self.socketio.emit(event,
                                              *args,
                                              namespace=ns_name,
                                              room=room)
                if ns_name is None:
                    return self.base_emit(event, *args, **kwargs)
                return request.namespace.socket[ns_name].base_emit(
                    event, *args, **kwargs)

            def send(self,
                     message,
                     json=False,
                     ns_name=None,
                     callback=None,
                     broadcast=False,
                     room=None):
                if broadcast or room:
                    if ns_name is None:
                        ns_name = self.ns_name
                    return self.socketio.send(message, json, ns_name, room)
                if ns_name is None:
                    return request.namespace.base_send(message, json, callback)
                return request.namespace.socket[ns_name].base_send(
                    message, json, callback)

        namespaces = {}
        for ns_name in self.messages.keys():
            namespaces[ns_name] = GenericNamespace
        return namespaces

    def _dispatch_message(self, app, namespace, message, args=[]):
        if namespace.ns_name not in self.messages:
            return
        if message not in self.messages[namespace.ns_name]:
            return
        with app.request_context(namespace.environ):
            request.namespace = namespace
            for k, v in namespace.session.items():
                session[k] = v
            ret = self.messages[namespace.ns_name][message](*args)
            for k, v in session.items():
                namespace.session[k] = v
            return ret

    def _join_room(self, namespace, room):
        if namespace.ns_name not in self.rooms:
            self.rooms[namespace.ns_name] = {}
        if room not in self.rooms[namespace.ns_name]:
            self.rooms[namespace.ns_name][room] = set()
        if namespace not in self.rooms[namespace.ns_name][room]:
            self.rooms[namespace.ns_name][room].add(namespace)
            return True
        return False

    def _leave_room(self, namespace, room):
        if namespace.ns_name in self.rooms:
            if room in self.rooms[namespace.ns_name]:
                if namespace in self.rooms[namespace.ns_name][room]:
                    self.rooms[namespace.ns_name][room].remove(namespace)
                    if len(self.rooms[namespace.ns_name][room]) == 0:
                        del self.rooms[namespace.ns_name][room]
                        if len(self.rooms[namespace.ns_name]) == 0:
                            del self.rooms[namespace.ns_name]

                    return True
        return False

    def on_message(self, message, handler, **options):
        ns_name = options.pop('namespace', '')
        if ns_name not in self.messages:
            self.messages[ns_name] = {}
        self.messages[ns_name][message] = handler

    def on(self, message, **options):
        def decorator(f):
            self.on_message(message, f, **options)
            return f

        return decorator

    def emit(self, event, *args, **kwargs):
        ns_name = kwargs.pop('namespace', None)
        if ns_name is None:
            ns_name = ''
        room = kwargs.pop('room', None)
        if room:
            for client in self.rooms.get(ns_name, {}).get(room, set()):
                client.base_emit(event, *args, **kwargs)
        else:
            if self.server:
                for sessid, socket in self.server.sockets.items():
                    if socket.active_ns.get(ns_name):
                        socket[ns_name].base_emit(event, *args, **kwargs)

    def send(self, message, json=False, namespace=None, room=None):
        ns_name = namespace
        if ns_name is None:
            ns_name = ''
        if room:
            for client in self.rooms.get(ns_name, {}).get(room, set()):
                client.base_send(message, json)
        else:
            if self.server:
                for sessid, socket in self.server.sockets.items():
                    if socket.active_ns.get(ns_name):
                        socket[ns_name].base_send(message, json)

    def run(self, app, host=None, port=None, **kwargs):
        if host is None:
            host = '127.0.0.1'
        if port is None:
            server_name = app.config['SERVER_NAME']
            if server_name and ':' in server_name:
                port = int(server_name.rsplit(':', 1)[1])
            else:
                port = 5000
        # don't allow override of resource, otherwise allow SocketIOServer
        # kwargs to be passed through
        kwargs.pop('resource', None)
        self.server = SocketIOServer((host, port),
                                     app.wsgi_app,
                                     resource='socket.io',
                                     **kwargs)
        if app.debug:

            def run_server():
                self.server.serve_forever()

            if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
                _log('info', ' * Running on http://%s:%d/' % (host, port))
            run_with_reloader(run_server)
        else:
            self.server.serve_forever()

    def test_client(self, app, namespace=None):
        return SocketIOTestClient(app, self, namespace)
コード例 #49
0
ファイル: __init__.py プロジェクト: MadAd360/GoGramming
 def run_server():
     server = SocketIOServer((host, port),
                             app.wsgi_app,
                             resource='socket.io')
     server.serve_forever()
コード例 #50
0
ファイル: server.py プロジェクト: sfeller/DatabaseScripts
def main():
    global VERBOSE
    global mdb
    global collection
    global port

    #default access info
    awsAccessKey = 'AKIAJICPBE3SSHW5SR7A'
    awsSecretKey = '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'
    awsBucket = 'aqueti.data'

    #parse inputs
    # parse command line arguments
    parser = argparse.ArgumentParser(description='Python server')

    parser.add_argument('-v',
                        action='store_const',
                        dest='VERBOSE',
                        const='True',
                        help='VERBOSE output')
    parser.add_argument('-vv',
                        action='store_const',
                        dest='VERBOSE2',
                        const='True',
                        help='VERBOSE output')
    parser.add_argument('-a',
                        action='store',
                        dest='aws_access',
                        help='AWS access code')
    parser.add_argument('-s',
                        action='store',
                        dest='aws_secret',
                        help='path to data')
    parser.add_argument('-b',
                        action='store',
                        dest='bucket',
                        help='S3 Bucket with data')
    """
   parser.add_argument('-p', action='store_const', dest='printout', const='True', help='print contents of JSON file')
   parser.add_argument('-d', action='store', dest='path', help='path to data')
   parser.add_argument('-u', action='store_const', dest='update', const='True', help='update records')
   parser.add_argument('-c', action='store', dest='collection', help='collection (table) to use')
   """
    parser.add_argument('dbase', help='database name')

    args = parser.parse_args()

    #set VERBOSE flag as requested
    if args.VERBOSE:
        VERBOSE = 1

    if args.VERBOSE2:
        VERBOSE = 2
        print "VERBOSE=2"

    #extract relevant parameters
    if VERBOSE > 1:
        print "Using database " + args.dbase

    ##################################################
    # connect to database and AWS server (if needed)
    ##################################################
    #connect to database
    mdb = MDB.MDB()
    if VERBOSE > 1:
        print "Connecting to mongodb: " + args.dbase
    try:
        rc = mdb.connect(args.dbase)
    except:
        print "MDB: Unable to connect to database: " + args.dbase
        return -1

#   if args.aws_access:
#      awsAccessKey = args.aws_access

#   if args.aws_secret:
#      awsSecretKey = arts.aws_secret

#   if args.bucket:
#      awsBucket = args.bucket

# Connect to AWS class
#sdf - need to make this optional
#   aws=AWS.AWS()
#   aws.setVerbose( VERBOSE );

#   if VERBOSE > 1:
#      print "Connecting to AWS: "+awsAccessKey+"/"+awsSecretKey
#   try:
#      aws.connect( awsAccessKey, awsSecretKey )
#   except:
#      print "Unable to connect to AWS. Please check inputs"
#      return -1

    print "Starting the server on port " + str(port) + "!"
    sio_server = SocketIOServer(('', port), chat, policy_server=False)
    sio_server.serve_forever()
def main():
    parser = argparse.ArgumentParser(description='Marteau Server')
    parser.add_argument('config', help='Config file', nargs='?')
    parser.add_argument('--version',
                        action='store_true',
                        default=False,
                        help='Displays Marteau version and exits.')
    parser.add_argument('--log-level',
                        dest='loglevel',
                        default='info',
                        choices=LOG_LEVELS.keys() +
                        [key.upper() for key in LOG_LEVELS.keys()],
                        help="log level")
    parser.add_argument('--log-output',
                        dest='logoutput',
                        default='-',
                        help="log output")
    parser.add_argument('--host', help='Host', default='0.0.0.0')
    parser.add_argument('--port', help='Port', type=int, default=8080)
    args = parser.parse_args()

    if args.version:
        print(__version__)
        sys.exit(0)

    if args.config is None:
        parser.print_usage()
        sys.exit(0)

    # configure the logger
    configure_logger(logger, args.loglevel, args.logoutput)

    # loading the config file
    config = Config(args.config)

    # loading the app & the queue
    global_config = {}
    if config.has_section('marteau'):
        settings = config.get_map('marteau')
    else:
        settings = {}

    # check is redis is running
    if not redis_available():
        raise IOError('Marteau needs Redis to run.')

    # loading the fixtures plugins
    for fixture in settings.get('fixtures', []):
        import_string(fixture)

    logger.info('Loaded plugins: %s' % ', '.join(get_fixtures()))

    app = webapp(global_config, **settings)
    try:
        httpd = SocketIOServer((args.host, args.port),
                               app,
                               resource="socket.io",
                               policy_server=False)
        logger.info('Hammer ready, at http://%s:%s. Where are the nails ?' %
                    (args.host, args.port))
        httpd.serve_forever()
    except KeyboardInterrupt:
        sys.exit(0)
    finally:
        logger.info('Bye!')
コード例 #52
0
def socketio_server(q):
    server = SocketIOServer(('0.0.0.0', 0), SocketApp(), policy_server=False)
    server.start()
    port = server.socket.getsockname()[1]
    q.put(port)
    server.serve_forever()
コード例 #53
0
ファイル: serve_tests.py プロジェクト: sajal/socketIO-client
'Launch this server in another terminal window before running tests'
from socketio import socketio_manage
from socketio.namespace import BaseNamespace
from socketio.server import SocketIOServer


class Namespace(BaseNamespace):
    def on_aaa(self, *args):
        self.socket.send_packet(
            dict(type='event', name='ddd', args=args, endpoint=self.ns_name))


class Application(object):
    def __call__(self, environ, start_response):
        socketio_manage(environ, {
            '': Namespace,
            '/chat': Namespace,
            '/news': Namespace,
        })


if __name__ == '__main__':
    socketIOServer = SocketIOServer(('0.0.0.0', 8000), Application())
    socketIOServer.serve_forever()
コード例 #54
0
class SocketIO(object):
    """Create a Flask-SocketIO server.

    :param app: The flask application instance. If the application instance
                isn't known at the time this class is instantiated, then call
                ``socketio.init_app(app)`` once the application instance is
                available.
    """
    def __init__(self, app=None):
        if app:
            self.init_app(app)
        self.messages = {}
        self.rooms = {}
        self.server = None

        self.exception_handlers = {}
        self.default_exception_handler = None

    def init_app(self, app):
        app.wsgi_app = _SocketIOMiddleware(app, self)

    def _get_namespaces(self, base_namespace=BaseNamespace):
        class GenericNamespace(base_namespace):
            socketio = self
            base_emit = base_namespace.emit
            base_send = base_namespace.send

            def initialize(self):
                self.rooms = set()

            def process_event(self, packet):
                if self.socketio.server is None:
                    self.socketio.server = self.environ['socketio'].server
                message = packet['name']
                args = packet['args']
                app = self.request
                return self.socketio._dispatch_message(app, self, message,
                                                       args)

            def join_room(self, room):
                if self.socketio._join_room(self, room):
                    self.rooms.add(room)

            def leave_room(self, room):
                if self.socketio._leave_room(self, room):
                    self.rooms.remove(room)

            def close_room(self, room):
                self.socketio._close_room(self, room)

            def recv_connect(self):
                if self.socketio.server is None:
                    self.socketio.server = self.environ['socketio'].server
                ret = super(GenericNamespace, self).recv_connect()
                app = self.request
                self.socketio._dispatch_message(app, self, 'connect')
                return ret

            def recv_disconnect(self):
                if self.socketio.server is None:
                    self.socketio.server = self.environ['socketio'].server
                app = self.request
                self.socketio._dispatch_message(app, self, 'disconnect')
                self.socketio._leave_all_rooms(self)
                return super(GenericNamespace, self).recv_disconnect()

            def recv_message(self, data):
                if self.socketio.server is None:
                    self.socketio.server = self.environ['socketio'].server
                app = self.request
                return self.socketio._dispatch_message(app, self, 'message',
                                                       [data])

            def recv_json(self, data):
                if self.socketio.server is None:
                    self.socketio.server = self.environ['socketio'].server
                app = self.request
                return self.socketio._dispatch_message(app, self, 'json',
                                                       [data])

            def emit(self, event, *args, **kwargs):
                ns_name = kwargs.pop('namespace', None)
                broadcast = kwargs.pop('broadcast', False)
                room = kwargs.pop('room', None)
                if broadcast or room:
                    if ns_name is None:
                        ns_name = self.ns_name
                    return self.socketio.emit(event,
                                              *args,
                                              namespace=ns_name,
                                              room=room)
                if ns_name is None:
                    return self.base_emit(event, *args, **kwargs)
                return request.namespace.socket[ns_name].base_emit(
                    event, *args, **kwargs)

            def send(self,
                     message,
                     json=False,
                     ns_name=None,
                     callback=None,
                     broadcast=False,
                     room=None):
                if broadcast or room:
                    if ns_name is None:
                        ns_name = self.ns_name
                    return self.socketio.send(message, json, ns_name, room)
                if ns_name is None:
                    return request.namespace.base_send(message, json, callback)
                return request.namespace.socket[ns_name].base_send(
                    message, json, callback)

            def disconnect(self, silent=False):
                self.socketio._leave_all_rooms(self)
                return super(GenericNamespace, self).disconnect(silent)

        namespaces = dict(
            (ns_name, GenericNamespace) for ns_name in self.messages)
        return namespaces

    def _dispatch_message(self, app, namespace, message, args=[]):
        if namespace.ns_name not in self.messages:
            return
        if message not in self.messages[namespace.ns_name]:
            return
        with app.request_context(namespace.environ):
            request.namespace = namespace
            request.event = {"message": message, "args": args}
            for k, v in namespace.session.items():
                session[k] = v
            ret = self.messages[namespace.ns_name][message](*args)
            for k, v in session.items():
                namespace.session[k] = v
            return ret

    def _join_room(self, namespace, room):
        if namespace.ns_name not in self.rooms:
            self.rooms[namespace.ns_name] = {}
        if room not in self.rooms[namespace.ns_name]:
            self.rooms[namespace.ns_name][room] = set()
        if namespace not in self.rooms[namespace.ns_name][room]:
            self.rooms[namespace.ns_name][room].add(namespace)
            return True
        return False

    def _leave_room(self, namespace, room):
        if namespace.ns_name in self.rooms:
            if room in self.rooms[namespace.ns_name]:
                if namespace in self.rooms[namespace.ns_name][room]:
                    self.rooms[namespace.ns_name][room].remove(namespace)
                    if len(self.rooms[namespace.ns_name][room]) == 0:
                        del self.rooms[namespace.ns_name][room]
                        if len(self.rooms[namespace.ns_name]) == 0:
                            del self.rooms[namespace.ns_name]

                    return True
        return False

    def _close_room(self, namespace, room):
        self.close_room(room, namespace.ns_name)

    def _leave_all_rooms(self, namespace):
        if namespace.ns_name in self.rooms:
            for room in self.rooms[namespace.ns_name].copy():
                self._leave_room(namespace, room)

    def _on_message(self, message, handler, namespace=''):
        if namespace not in self.messages:
            self.messages[namespace] = {}
        self.messages[namespace][message] = handler

    def on(self, message, namespace=''):
        """Decorator to register a SocketIO event handler.

        This decorator must be applied to SocketIO event handlers. Example::

            @socketio.on('my event', namespace='/chat')
            def handle_my_custom_event(json):
                print('received json: ' + str(json))

        :param message: The name of the event. Use ``'message'`` to define a
                        handler that takes a string payload, ``'json'`` to
                        define a handler that takes a JSON blob payload,
                        ``'connect'`` or ``'disconnect'`` to create handlers
                        for connection and disconnection events, or else, use a
                        custom event name, and use a JSON blob as payload.
        :param namespace: The namespace on which the handler is to be
                          registered. Defaults to the global namespace.
        """
        if namespace in self.exception_handlers or \
                self.default_exception_handler is not None:

            def decorator(event_handler):
                def func(*args, **kwargs):
                    try:
                        return event_handler(*args, **kwargs)
                    except:
                        handler = self.exception_handlers.get(
                            namespace, self.default_exception_handler)
                        type, value, traceback = sys.exc_info()
                        return handler(value)

                self._on_message(message, func, namespace)
                return func
        else:

            def decorator(event_handler):
                self._on_message(message, event_handler, namespace)
                return event_handler

        return decorator

    def on_error(self, namespace=''):
        """Decorator to define a custom error handler for SocketIO events.

        This decorator can be applied to a function that acts as an error
        handler for a namespace. This handler will be invoked when a SocketIO
        event handler raises an exception. The handler function must accept one
        argument, which is the exception raised. Example::

            @socketio.on_error(namespace='/chat')
            def chat_error_handler(e):
                print('An error has occurred: ' + str(e))

        :param namespace: The namespace for which to register the error
                          handler. Defaults to the global namespace.
        """
        def decorator(exception_handler):
            if not callable(exception_handler):
                raise ValueError('exception_handler must be callable')
            self.exception_handlers[namespace] = exception_handler

        return decorator

    def on_error_default(self, exception_handler):
        """Decorator to define a default error handler for SocketIO events.

        This decorator can be applied to a function that acts as a default
        error handler for any namespaces that do not have a specific handler.
        Example::

            @socketio.on_error_default
            def error_handler(e):
                print('An error has occurred: ' + str(e))
        """
        if not callable(exception_handler):
            raise ValueError('exception_handler must be callable')
        self.default_exception_handler = exception_handler

    def emit(self, event, *args, **kwargs):
        """Emit a server generated SocketIO event.

        This function emits a user-specific SocketIO event to one or more
        connected clients. A JSON blob can be attached to the event as payload.
        This function can be used outside of a SocketIO event context, so it is
        appropriate to use when the server is the originator of an event, for
        example as a result of a regular HTTP message. Example::

            @app.route('/ping')
            def ping():
                socketio.emit('ping event', {'data': 42}, namespace='/chat')

        :param event: The name of the user event to emit.
        :param args: A dictionary with the JSON data to send as payload.
        :param namespace: The namespace under which the message is to be sent.
                          Defaults to the global namespace.
        :param room: Send the message to all the users in the given room. If
                     this parameter is not included, the event is sent to
                     all connected users.
        """
        ns_name = kwargs.pop('namespace', '')
        room = kwargs.pop('room', None)
        if room is not None:
            for client in self.rooms.get(ns_name, {}).get(room, set()):
                client.base_emit(event, *args, **kwargs)
        elif self.server:
            for sessid, socket in self.server.sockets.items():
                if socket.active_ns.get(ns_name):
                    socket[ns_name].base_emit(event, *args, **kwargs)

    def send(self, message, json=False, namespace=None, room=None):
        """Send a server-generated SocketIO message.

        This function sends a simple SocketIO message to one or more connected
        clients. The message can be a string or a JSON blob. This is a simpler
        version of ``emit()``, which should be preferred. This function can be
        used outside of a SocketIO event context, so it is appropriate to use
        when the server is the originator of an event.

        :param message: The message to send, either a string or a JSON blob.
        :param json: ``True`` if ``message`` is a JSON blob, ``False``
                     otherwise.
        :param namespace: The namespace under which the message is to be sent.
                          Defaults to the global namespace.
        :param room: Send the message only to the users in the given room. If
                     this parameter is not included, the message is sent to
                     all connected users.
        """
        ns_name = namespace
        if ns_name is None:
            ns_name = ''
        if room:
            for client in self.rooms.get(ns_name, {}).get(room, set()):
                client.base_send(message, json)
        else:
            if self.server:
                for sessid, socket in self.server.sockets.items():
                    if socket.active_ns.get(ns_name):
                        socket[ns_name].base_send(message, json)

    def close_room(self, room, namespace=''):
        """Close a room.

        This function removes any users that are in the given room and then
        deletes the room from the server. This function can be used outside
        of a SocketIO event context.

        :param room: The name of the room to close.
        :param namespace: The namespace under which the room exists. Defaults
                          to the global namespace.
        """
        if namespace in self.rooms:
            if room in self.rooms[namespace]:
                for ns in self.rooms[namespace][room].copy():
                    self._leave_room(ns, room)

    def run(self, app, host=None, port=None, **kwargs):
        """Run the SocketIO web server.

        :param app: The Flask application instance.
        :param host: The hostname or IP address for the server to listen on.
                     Defaults to 127.0.0.1.
        :param port: The port number for the server to listen on. Defaults to
                     5000.
        :param use_reloader: ``True`` to enable the Flask reloader, ``False``
                             to disable it.
        :param resource: The SocketIO resource name. Defaults to
                         ``'socket.io'``. Leave this as is unless you know what
                         you are doing.
        :param transports: Optional list of transports to allow. List of
                           strings, each string should be one of
                           handler.SocketIOHandler.handler_types.
        :param policy_server: Boolean describing whether or not to use the
                              Flash policy server.  Defaults to ``True``.
        :param policy_listener: A tuple containing (host, port) for the
                                policy server. This is optional and used only
                                if policy server is set to true.  Defaults to
                                0.0.0.0:843.
        :param heartbeat_interval: The timeout for the server, we should
                                   receive a heartbeat from the client within
                                   this interval. This should be less than the
                                   ``heartbeat_timeout``.
        :param heartbeat_timeout: The timeout for the client when it should
                                  send a new heartbeat to the server. This
                                  value is sent to the client after a
                                  successful handshake.
        :param close_timeout: The timeout for the client, when it closes the
                              connection it still X amounts of seconds to do
                              re-open of the connection. This value is sent to
                              the client after a successful handshake.
        :param log_file: The file in which you want the PyWSGI server to write
                         its access log.  If not specified, it is sent to
                         ``stderr`` (with gevent 0.13).
        """
        if host is None:
            host = '127.0.0.1'
        if port is None:
            server_name = app.config['SERVER_NAME']
            if server_name and ':' in server_name:
                port = int(server_name.rsplit(':', 1)[1])
            else:
                port = 5000
        resource = kwargs.pop('resource', 'socket.io')
        use_reloader = kwargs.pop('use_reloader', app.debug)

        self.server = SocketIOServer((host, port),
                                     app.wsgi_app,
                                     resource=resource,
                                     **kwargs)
        if use_reloader:
            # monkey patching is required by the reloader
            from gevent import monkey
            monkey.patch_all()

            def run_server():
                self.server.serve_forever()

            if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
                _log('info', ' * Running on http://%s:%d/' % (host, port))
            run_with_reloader(run_server)
        else:
            _log('info', ' * Running on http://%s:%d/' % (host, port))
            self.server.serve_forever()

    def test_client(self, app, namespace=None):
        """Return a simple SocketIO client that can be used for unit tests."""
        return SocketIOTestClient(app, self, namespace)
コード例 #55
0
def socketio_server():
    server = SocketIOServer(('0.0.0.0', port),
                            SocketApp(),
                            policy_server=False)
    server.start()
    server.serve_forever()
コード例 #56
0
    404 error handler
    used if a non existant route
    is requested
    """
    return render_template('404.html'), 404


@app.errorhandler(500)
def page_not_found(exc):
    """
    500 error handler
    used if there is a server error
    """
    return render_template('500.html'), 500


if __name__ == '__main__':
    analyzer = Analyzer()
    server = SocketIOServer(('', PORT), app, resource="socket.io")
    tw_thread = TweetWeather(server, analyzer, name="Tweet-Weather-Thread")
    tw_thread.daemon = True
    gevent.spawn(tw_thread.new_post, server)
    gevent.spawn(tw_thread.connexion_lost, server)
    print "Application Started: http://localhost:5000"
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        tw_thread.stop()
        server.stop()
        sys.exit()
コード例 #57
0
ファイル: service.py プロジェクト: adoggie/PyDawn
class FlaskService(ServiceBase):
    TYPE = 'FlaskService'

    def __init__(self, name):
        super(FlaskService, self).__init__(name)
        self.app = None

        self.api_list = {}  # 注册api
        self.db = None
        self.blueprints = {}
        self.logger = Logger(__name__)
        self.isclosed = False
        self.thread = None
        self.server = None

    def init(self, cfgs, **kwargs):
        #from mantis.fundamental.application.app import instance
        if kwargs.has_key('logger'):
            self.logger = kwargs.get('logger')

        self.cfgs = cfgs
        if kwargs.has_key('app'):
            self.app = kwargs.get('app')
        else:
            static_path = os.getcwd() + '/static'
            template_path = os.getcwd() + '/templates'
            self.app = Flask(
                __name__,
                static_folder=static_path,
                template_folder=template_path
            )  # flask会自动将当前代码目录设置为项目根目录 root_path 导致读取templtes , sta它ic 目录失败

        Compress(self.app)  # okay
        # gzip = Gzip(app) # error

        active = self.getConfig().get('cfgs', {})
        for k, v in active.items():
            self.app.config[k] = v

        self.initCors()
        self.initDatabase()

        self.setupRequestHooks()
        self.initBlueprint()

        self.setupTemplates()

    def setupTemplates(self):
        from werkzeug.routing import BaseConverter
        from flask import Flask, send_file

        class RegexConverter(BaseConverter):
            def __init__(self, map, *args):
                self.map = map
                self.regex = args[0]

        self.app.url_map.converters['regex'] = RegexConverter

        @self.app.route('/<regex(".*\.html$"):template_name>')
        def _template_render(template_name):
            name = os.path.join(self.app.template_folder, template_name)
            return send_file(name)

    def initDatabase(self):
        global db
        if db.get() is None:
            self.db = SQLAlchemy(self.app)
            db.set(self.db)

    def getDatabase(self):
        return self.db

    def initCors(self):
        """
            https://flask-cors.readthedocs.io/en/latest/
        :return:
        """
        if self.getConfig().get('cors_enable', True):
            CORS(self.app)

    def getFlaskApp(self):
        return self.app

    def setupRequestHooks(self):
        self.app.before_request(self.onRequestBefore)
        self.app.teardown_request(self.onRequestTeardown)
        # self.app.after_request(self._requestAfter)  # todo. 导致 send_file 失败
        # 当利用send_file发送二进制数据时,after_request对返回数据进行日志处理,导致数据返回失败

    def _traceRequestInfo(self, opts):
        import json
        trace_data = {'url': request.url}
        if opts.get('header'):
            trace_data['headers'] = request.headers
        if opts.get('body'):
            trace_data['body'] = request.data.replace(
                '\n', ' ')[:opts.get('max_size')]
        return json.dumps(trace_data)

    def _traceResponseInfo(self, opts, response):
        import json
        trace_data = {'url': request.url}
        if opts.get('header'):
            trace_data['headers'] = response.headers
        if opts.get('body'):
            trace_data['body'] = response.data.replace(
                '\n', ' ')[:opts.get('max_size')]
        return json.dumps(trace_data)

    def onRequestBefore(self):
        # pass
        import time
        g.start_time = time.time()

        #
        # trace = self.getConfig().get('http_trace',{}).get('request',{})
        # options = trace.get('options',{'header':False,'body':False,'max_size':1024})
        # urls = trace.get('urls',[])
        # #sort urls by 'match' with desceding.
        # urls = sorted(urls,cmp = lambda x,y: cmp(len(x.get('match')) , len(y.get('match')) ) )
        # urls.reverse()
        #
        # text = ''
        # for url in urls:
        #     m = url.get('match')
        #     if m:
        #         opts = options.copy()
        #         opts['header'] = url.get('header',options.get('header'))
        #         opts['body'] = url.get('body',options.get('body'))
        #         opts['max_size'] = url.get('max_size',options.get('max_size'))
        #         if request.url.find(m) !=-1:
        #             text = self._traceRequestInfo(opts)
        #             break
        # level = self.getConfig().get('http_trace',{}).get('level','DEBUG')
        # text = 'HttpRequest: '+text
        # self.getLogger().log(level,text)

    def onRequestTeardown(self, e):
        pass

    def _requestAfter(self, response):

        trace = self.getConfig().get('http_trace', {}).get('response', {})
        options = trace.get('options', {
            'header': False,
            'body': False,
            'max_size': 1024
        })
        urls = trace.get('urls', [])

        urls = sorted(
            urls,
            cmp=lambda x, y: cmp(len(x.get('match')), len(y.get('match'))))
        urls.reverse()

        text = ''
        for url in urls:
            m = url.get('match')
            if m:
                opts = options.copy()
                opts['header'] = url.get('header', options.get('header'))
                opts['body'] = url.get('body', options.get('body'))
                opts['max_size'] = url.get('max_size', options.get('max_size'))
                if request.url.find(m) != -1:
                    text = self._traceResponseInfo(opts, response)
                    break
        level = self.getConfig().get('http_trace', {}).get('level', 'DEBUG')

        remote_addr = ''
        if request.headers.getlist("X-Forwarded-For"):
            remote_addr = request.headers.getlist("X-Forwarded-For")[0]
        else:
            remote_addr = request.remote_addr

        elapsed = int((time.time() - g.start_time) * 1000)
        text = 'HTTP %s %s %s %sms  ' % (remote_addr, request.method,
                                         request.url, elapsed)
        self.getLogger().log(level, text)

        return response

    def initBlueprint(self):

        cfgs = self.getConfig().get('blueprints', [])
        for cfg in cfgs:
            # module = import_module( cfgs.get('module'))
            if not cfg.get('register', True):
                continue
            package_name = cfg.get('name', '')
            package = cfg.get('package')
            package_url = cfg.get('url')
            modules = cfg.get('modules', [])
            for module in modules:
                module_name = module.get('name', )
                module_url = module.get("url", '')
                path = '%s.%s' % (package, module_name)
                load_module = import_module(path)

                app = Blueprint(module_name, path)
                self.blueprints[path] = app

                # api_module = {'name': u'%s.%s'%(package_name,module_name),'api_list':[]}
                module_name = u'%s.%s' % (package_name, module_name)
                self.api_list[module_name] = []

                routes = module.get('routes', [])
                for route in routes:
                    url = route.get('url', '')
                    name = route.get('name', '')
                    methods = filter(
                        lambda x: len(x) > 0,
                        route.get('methods', '').strip().upper().split(','))

                    if hasattr(load_module, name):
                        func = getattr(load_module, name)
                        path = package_url + module_url
                        path = path.replace('//', '/')
                        if methods:
                            app.route(url, methods=methods)(func)
                        else:
                            app.route(url)(func)
                        self.registerBlueprint(app, path)
                        path = path + '/' + url
                        path = path.replace('//', '/')
                        self.logger.debug('registered blueprint route:' + path)

                        api = {'url': path, 'methods': ('GET', )}

                        if methods:
                            api['methods'] = methods
                        self.api_list[module_name].append(api)

    def registerAPIs(self, manager):
        manager.register_http_service(self.api_list)

    # def _initLogger(self):
    #     from camel.biz.logging.logger import FlaskHttpRequestLogger
    #     return FlaskHttpRequestLogger(self.appId)

    # def start(self,block = True):
    #     # Application.run(self)
    #     http = self.getConfig().get('http')
    #     if http:
    #         self.app.run(host=http.get('host','127.0.0.1'),
    #             port = http.get('port',5000),
    #             threaded = http.get('threaded',True),
    #             debug = http.get('debug',True),
    #             process = http.get('process',1))

    def select_address(self):
        """
        修正http侦听地址 , 如果port未定义或者为0 ,则进行动态选定端口
        :return:
        """
        from mantis.fundamental.utils.network import select_address_port
        http = self.cfgs.get('http')

        if not http.get('port'):  # port 未定义或者为0
            start = 18900
            end = 18950
            address = select_address_port(http.get('host'), start, end)
            self.cfgs.get('http')['port'] = address[1]

    def start(self, block=True):
        self.select_address()

        http = self.getConfig().get('http')
        host = http.get('host', '127.0.0.1')
        port = http.get('port', 5000)
        # app = self.app

        # if http.get('debug', False):
        #     app.run(host,port,debug=True)
        # else:
        #     self.server = wsgi.WSGIServer(( host, port), app)
        #
        #     self.server.start()
        #     Application.run(self)
        # self.server = pywsgi.WSGIServer((host,port),app)
        # self.server.start()

        self.initHttpServer()

        if block:
            self.logger.info('Service: %s started, Listen on %s:%s ...' %
                             (self.name, host, port))
            self.server.serve_forever()
        else:
            self.thread = Thread(target=self.runThread)
            self.thread.setDaemon(True)
            self.thread.start()

    def initHttpServer(self):
        http = self.getConfig().get('http')
        host = http.get('host', '127.0.0.1')
        port = http.get('port', 5000)
        app = self.app
        from mantis.fundamental.application.use_gevent import USE_GEVENT

        print '--' * 20
        if USE_GEVENT:
            from gevent import pywsgi
            from socketio.server import SocketIOServer
            if http.get('websocket', False):
                self.server = SocketIOServer((host, port),
                                             app,
                                             resource="socket.io")
            else:
                self.server = pywsgi.WSGIServer((host, port), app)
                self.server.start()
        else:
            from wsgiref.simple_server import make_server
            self.server = make_server(host, port, app)

        self.logger.info('Service: %s started, Listen on %s:%s ...' %
                         (self.name, host, port))

    def runThread(self):
        # print 'xxxx-Service: %s started, Listen on %s:%s ...' % (self.name, host, port)
        self.server.serve_forever()

    def stop(self):
        from mantis.fundamental.application.use_gevent import USE_GEVENT

        if self.server:
            if USE_GEVENT:
                self.server.stop()
            else:
                self.server.shutdown()

    def registerBlueprint(self, bp, url):
        self.app.register_blueprint(bp, url_prefix=url)