예제 #1
0
    def __init__(self, port):
        """
        Constructor.
        """
        tornado_settings = {
            "static_path": os.path.join(os.path.dirname(__file__), "static"),
            "socket_io_port": port,
            'flash_policy_port': 843,
            'enabled_protocols': ['websocket',
                                  'flashsocket',
                                  'xhr-multipart',
                                  'xhr-polling'],
        }

        # The wrapper around our Django app.
        wsgi_app = tornado.wsgi.WSGIContainer(django.core.handlers.wsgi.WSGIHandler())

        self.application = tornado.web.Application([
                (r'/', tornado.web.FallbackHandler, {'fallback': wsgi_app}),
                (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': op.join(settings.ROOT, 'static')}),
                tornadio.get_router(CamprConnection).route(),
                (r'.*', tornado.web.FallbackHandler, {'fallback': wsgi_app}),
            ], **tornado_settings)

        self.server = None
예제 #2
0
파일: server.py 프로젝트: stas/exorcyber
 def __init__(self):
     file_root = path.normpath(path.dirname(__file__))
     router = tornadio.get_router(ExorCyberConnection)
     application = tornado.web.Application(
         [(r"/", StaticHandler),router.route()],
         enabled_protocols = [
             'websocket',
             'flashsocket',
         #    'xhr-multipart',
             'xhr-polling'
         ],
         socket_io_port = 8081,
         flash_policy_file = path.join(file_root, 'static/flashpolicy.xml'),
     )
     tornadio.server.SocketServer(application)
예제 #3
0
파일: serve.py 프로젝트: jcheadiv/apps-sdk
    def run(self):
        logging.info('\tStarting server. Access it at http://localhost:%s/' %
                (self.options['port'],))

        self.setup_config()
        tornado.options.parse_config_file(pkg_resources.resource_filename(
                'apps.data', 'serve.conf'))

        logging.getLogger().handlers = []
        tornado.options.enable_pretty_logging()
        logging.getLogger().setLevel(logging.INFO)

        application = tornado.web.Application([
                (r"/rpc", RPCHandler),
                (r"/proxy", ProxyHandler),
                (r"/.*", FileHandler),
                tornadio.get_router(ComChannel, resource='worker').route(),
                tornadio.get_router(BrowserChannel, resource='browser').route(),
                ], **{ "debug": options.debug,
                       "cookie": self.setup_cookie(),
                       "socket_io_port": int(self.options['port']) })
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(int(self.options['port']))
        tornado.ioloop.IOLoop.instance().start()
예제 #4
0
파일: jam.py 프로젝트: achur/JamSession
 def __init__(self):
   Router = tornadio.get_router(JamSessionConnection, resource='JamSessionSocket', extra_re=r'\S+', extra_sep='/')
   handlers = [
     (r'/', UnittestHandler),
     (r'/(.*?)', ScoreHandler),
     Router.route(),
     ]
   settings = dict(
     cookie_secret="12oETzKXQAG5OkPL5gEmGeJJFuYh7EQQp2XdTP1o/Vo=",
     template_path=os.path.join(os.path.dirname(__file__), "templates"),
     static_path=os.path.join(os.path.dirname(__file__), "static"),
     xsrf_cookies=False,
     enabled_protocols=['websocket', 'xhr-multipart', 'xhr-polling'],
     debug=options.debug,
     socket_io_port=options.port
     )
   tornado.web.Application.__init__(self, handlers, **settings)
예제 #5
0
def main():
    queue.start_queue(settings.FANOUT_HOST, settings.FANOUT_PORT)

    if settings.MOBILE:
        geo_master = GeoMaster()
    else:
        geo_master = None
    
    NotifRouter = tornadio.get_router(NotifConnectionFactory(queue_master=queue.master, geo_master=geo_master), settings=kwargs)

    #configure the Tornado application
    application = tornado.web.Application(
            [NotifRouter.route()], 
            **kwargs
    )

    tornadio.server.SocketServer(application, 
        xheaders=xheaders, 
        ssl_options=ssl_options
    )
예제 #6
0
파일: chatroom.py 프로젝트: xigit/tornadio
    def on_open(self, *args, **kwargs):
        self.participants.add(self)
        self.send("Welcome!")

    def on_message(self, message):
        for p in self.participants:
            p.send(message)

    def on_close(self):
        self.participants.remove(self)
        for p in self.participants:
            p.send("A user has left.")

#use the routes classmethod to build the correct resource
ChatRouter = tornadio.get_router(ChatConnection)

#configure the Tornado application
application = tornado.web.Application(
    [(r"/", IndexHandler), ChatRouter.route()],
    enabled_protocols = ['websocket',
                         'flashsocket',
                         'xhr-multipart',
                         'xhr-polling'],
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port = 8001
)

if __name__ == "__main__":
    import logging
예제 #7
0
파일: view.py 프로젝트: k1000/chatroomio
        return msg

    def on_close(self):
        del self.participants[self.nick]
        msg = dict(
            msg ="%s has left." % self.nick 
            ,type="info"
            ,nick=self.nick
            ,room=self.room
        )
        self.broadcast( msg, self.room )
    
    def on_signal(sender, **kwargs):
        print kwargs
        self.broadcast( **kwargs )

    @classmethod
    def send_msg(cls, msssage, room=None):
        cls.broadcast( msg, self.room )

    @classmethod
    def who(cls, room=None) :
        if room:
            return [name for name, participant in cls.participants.items() if participant.room == room ]
        else:
            return cls.participants.keys()



ChatRouter = tornadio.get_router(ChatConnection, resource="chat")
예제 #8
0
    @staticmethod
    def notify():
        listeners = set()
        for namespace in ClientsConnection.namespaces.values():
            if not namespace['listeners'] or namespace['last_notified_value'] == namespace['members']:
                continue
            for ws in namespace['listeners']:
                ws.notif[namespace['name']] = namespace['members']
                listeners.add(ws)
            namespace['last_notified_value'] = namespace['members']
        for ws in listeners:
            ClientsConnection._send_notif(ws)

PeriodicCallback(ClientsConnection.notify, NOTIFY_INTERVAL).start()

ClientsRouter = tornadio.get_router(ClientsConnection)

#configure the Tornado application
application = tornado.web.Application(
    [(r"/ns/(.*)", IndexHandler), ClientsRouter.route()],
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    flash_policy_port = 843,
    socket_io_port = 80,
)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(logging.DEBUG)

    tornadio.server.SocketServer(application)
예제 #9
0
            self.write({ "error" : "Could not save file." })
            self.event.success = False
        self.event.end = datetime.now()
        db.flush()
        gc.collect()

application = tornado.web.Application([
    (r"/(favicon.ico)", tornado.web.StaticFileHandler, {"path": "static/img/"}),
    (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "static/"}),
    (r"/monitor[/]?([^/]+)?[/]?(.*)", MonitorHandler), #Fix this
    (r"/upload", UploadHandler),
    (r"/share/(%s)" % config.uid_re, ShareHandler),
    (r"/download/(%s)" % config.uid_re, DownloadHandler),
    (r"/", MainHandler),
    tornadio.get_router(
        MonitorSocket,
        resource = config.monitor_resource
    ).route(),
    tornadio.get_router(
        ProgressSocket,
        resource = config.progress_resource,
        extra_re = config.uid_re,
        extra_sep = config.socket_extra_sep
    ).route()],
    socket_io_port = config.socket_io_port,
    enabled_protocols = ['websocket', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'],
    )


if __name__ == "__main__":
    Daemon()
ROOT = op.normpath(op.dirname(__file__))



#just render the input.html page        
class InputHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")

#just render the screen.html page
class ScreenHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("screen.html")
        
#routers will autoamagicly generate the right urls for their resources
ScreenRouter = tornadio.get_router(ScreenConnection, resource='screen')
InputRouter = tornadio.get_router(PlayerConnection, resource='input')

#configure the urls for the tornado server
routes = [(r"/", InputHandler),
          (r"/input", InputHandler),
          InputRouter.route(),
          (r"/screen", ScreenHandler),
          ScreenRouter.route()
          ]

settings = {"static_path": os.path.join(os.path.dirname(__file__), "static")}

#set up and run the actual server process
application = tornado.web.Application(
    routes,
예제 #11
0
            'at': self.now,
            'type': 'message',
        }
        if broadcast:
            self.broadcast(data, but_me=but_me)
        else:
            self.send(data)

    def on_message(self, message):
        db.append("message", message)
        self.send_chat_message(message, True)

    def on_close(self):
        self.send_system_info("A user has left", True)

ChatRouter = tornadio.get_router(ChatParticipant, resource='chat')
ClockRouter = tornadio.get_router(ClockConnection, resource='clock')

application = Application(
    [
        (r"/", MainHandler),
        ChatRouter.route(),
        ClockRouter.route(),
    ],
    template_path=LOCAL_FILE('views'),
    static_path=LOCAL_FILE('public'),
    socket_io_port=8000,
    debug=True,
)

if __name__ == "__main__":
예제 #12
0
            self.send(json.dumps({"action": "connected"}))
        elif message['action'] == 'rcon':
            self.send(
                json.dumps({
                    'action': 'rcon',
                    'orginalCommand': message['command'],
                    'output': self.server.rcon(message['command'])
                }))

    def on_close(self):
        if self.server:
            self.server.disconnect()


#use the routes classmethod to build the correct resource
RconRouter = tornadio.get_router(SourceRconConnection)

#configure the Tornado application
application = tornado.web.Application([RconRouter.route()],
                                      enabled_protocols=[
                                          'websocket', 'flashsocket',
                                          'xhr-multipart', 'xhr-polling'
                                      ],
                                      flash_policy_port=843,
                                      flash_policy_file=op.join(
                                          ROOT, 'flashpolicy.xml'),
                                      socket_io_port=8001)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(logging.DEBUG)
예제 #13
0
        feed = Feed()

        # Set the feed/channel level properties
        feed.feed["title"] = "pkt.li"
        feed.feed["author"] = "pkt.li"
        feed.feed["link"] = "http://pkt.li/banks/rss"

        # Create items and add to the feed
        for item in rss_items:
            feed.items.append(item)

        # Print the feed to stdout in various formats
        self.content_type = 'application/atom+xml'
        self.write(feed.format_atom_string())

if __name__ == '__main__':
    settings = {
        'template_path': os.path.join(os.path.dirname(__file__), 'templates'),
        'static_path': os.path.join(os.path.dirname(__file__), 'static'),
    }
    FIStatusRouter = tornadio.get_router(FIStatusSocketConnection, {
        'enabled_protocols': ['websocket', 'xhr-multipart', 'xhr-polling']
    }, resource='fistatus')
    app = tornado.web.Application([
        (r'favicon.ico', tornado.web.StaticFileHandler),
        (r'/fistatus', FIStatusHandler),
        FIStatusRouter.route(),
        (r'/rss', RSSHandler),
    ], socket_io_port=8000, debug=True, **settings)
    tornadio.server.SocketServer(app)
예제 #14
0
#!/usr/bin/env python

import tornadio, tornadio.server
import tornado.web

class MyConnection(tornadio.SocketConnection):
    def on_message(self,message):
        print message

MyRouter = tornadio.get_router(MyConnection)

application = tornado.web.Application(
    [MyRouter.route()],
    socket_io_port=9000)

socketio_server = tornadio.server.SocketServer(application)

#application.listen(8888)
#tornado.ioloop.IOLoop.instance().start()
예제 #15
0
    def on_message(self, message):
        pass

    def on_close(self):
        server.clients.remove(self)
        packet = {'left': {'id': self.id}}
        server.broadcast(packet)


settings = {
    'static_path': op.join(op.dirname(__file__), 'static'),
}

#use the routes classmethod to build the correct resource
Router = tornadio.get_router(Client)

#configure the Tornado application
application = tornado.web.Application(
    [(r"/static/(.*)", tornado.web.StaticFileHandler,
      dict(path=settings['static_path'])), (r"/", IndexHandler),
     Router.route()],
    enabled_protocols=[
        'websocket', 'flashsocket', 'xhr-multipart', 'xhr-polling'
    ],
    flash_policy_port=843,
    flash_policy_file=op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port=11001)

import zmq
예제 #16
0
        self.send("Welcome!")

    def on_message(self, message):
        for p in self.participants:
            p.send(message)

    def on_close(self):
        self.participants.remove(self)
        for p in self.participants:
            p.send("A user has left.")


#use the routes classmethod to build the correct resource
ChatRouter = tornadio.get_router(
    ChatConnection, {
        'enabled_protocols':
        ['websocket', 'flashsocket', 'xhr-multipart', 'xhr-polling']
    })

#configure the Tornado application
application = tornado.web.Application(
    [(r"/", IndexHandler), ChatRouter.route()],
    flash_policy_port=843,
    flash_policy_file=op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port=8001)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(logging.DEBUG)

    tornadio.server.SocketServer(application)
예제 #17
0
파일: ping.py 프로젝트: kmike/tornadio
import tornado.web
import tornadio
import tornadio.router
import tornadio.server

ROOT = op.normpath(op.dirname(__file__))

class IndexHandler(tornado.web.RequestHandler):
    """Regular HTTP handler to serve the ping page"""
    def get(self):
        self.render("index.html")

class PingConnection(tornadio.SocketConnection):
    def on_message(self, message):
        message['server'] = str(datetime.now())
        self.send(message)

#use the routes classmethod to build the correct resource
PingRouter = tornadio.get_router(PingConnection)

#configure the Tornado application
application = tornado.web.Application(
    [(r"/", IndexHandler), PingRouter.route()],
    socket_io_port = 8001,
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml')
)

if __name__ == "__main__":
    tornadio.server.SocketServer(application)
예제 #18
0
        listeners = set()
        for namespace in ClientsConnection.namespaces.values():
            if not namespace['listeners'] or namespace[
                    'last_notified_value'] == namespace['members']:
                continue
            for ws in namespace['listeners']:
                ws.notif[namespace['name']] = namespace['members']
                listeners.add(ws)
            namespace['last_notified_value'] = namespace['members']
        for ws in listeners:
            ClientsConnection._send_notif(ws)


PeriodicCallback(ClientsConnection.notify, NOTIFY_INTERVAL).start()

ClientsRouter = tornadio.get_router(ClientsConnection)

#configure the Tornado application
application = tornado.web.Application(
    [(r"/ns/(.*)", IndexHandler),
     ClientsRouter.route()],
    flash_policy_file=op.join(ROOT, 'flashpolicy.xml'),
    flash_policy_port=843,
    socket_io_port=80,
)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(logging.DEBUG)

    tornadio.server.SocketServer(application)
예제 #19
0
        server.send(self, packet)
        
    def on_message(self, message):
        pass

    def on_close(self):
        server.clients.remove(self)
        packet = {'left': {'id': self.id}}
        server.broadcast(packet)
        
settings = {
    'static_path': op.join(op.dirname(__file__), 'static'),
}

#use the routes classmethod to build the correct resource
Router = tornadio.get_router(Client)

#configure the Tornado application
application = tornado.web.Application(
    [(r"/static/(.*)", tornado.web.StaticFileHandler, dict(path=settings['static_path'])), 
     (r"/", IndexHandler), 
     Router.route()],
    enabled_protocols = ['websocket',
                         'flashsocket',
                         'xhr-multipart',
                         'xhr-polling'],
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port = 11001
)
예제 #20
0
"""

    Command & Control server for Plone IDE.


    This server communicates on the native layer e.g. start/stops
    processing over full duplex Socket.IO channel to the Javascript layer.


"""

import tornado
import tornadio

class CCConnection(tornadio.SocketConnection):

    def on_message(self, message):
        print "Ich bin ein mezzage"
        pass


CCRouter = tornadio.get_router(CCConnection)

application = tornado.web.Application([CCRouter.route()], socket_io_port = 8085)

예제 #21
0
                # Send this new client to all existing ones
                client.send({"new_client": username})
            self.username = username
            
        elif "new_message" in message and self.username:
            clients = client_collection.get_clients(self.username)
            for name, client in clients:
                client.send(message)


if __name__ == "__main__":
    logging.getLogger().setLevel(logging.WARNING)
    root_dir = op.normpath(op.dirname(__file__))
    static_path = op.join(root_dir, "static")
    
    SocketIOConnectionRouter = tornadio.get_router(SocketIOConnection)

    # Configure the Tornado application
    application = tornado.web.Application(
        [(r"/favicon.ico", tornado.web.StaticFileHandler, {"path":static_path}),
        (r"/", LobbyHandler),
        (r"/lobby.html", LobbyHandler),
        (r"/chatroom.html", ChatRoomHandler),
        SocketIOConnectionRouter.route()],
        static_path = static_path,
        enabled_protocols = ['websocket',
                             'flashsocket',
                             'xhr-multipart',
                             'xhr-polling'],
        flash_policy_port = FLASH_POLICY_PORT,
        flash_policy_file = op.join(static_path, 'flashpolicy.xml'),
예제 #22
0
                json_msg["timestamp"] = timestamp

                self.send(json_msg)

            self.participants.add(self)
        elif message["action"] == "done":
            self.ready = True

    def on_close(self):
        self.participants.remove(self);

#use the routes classmethod to build the correct resource
LabSenseRouter = tornadio.get_router(LabSenseConnection, {
    'enabled_protocols': [
        'websocket',
        'flashsocket',
        'xhr-multipart',
        'xhr-polling'
    ]
})

#configure the Tornado application
application = tornado.web.Application(
    [LabSenseRouter.route()],
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port = 8001
)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(logging.DEBUG)
예제 #23
0
            'type': 'message',
        }
        if broadcast:
            self.broadcast(data, but_me=but_me)
        else:
            self.send(data)

    def on_message(self, message):
        db.append("message", message)
        self.send_chat_message(message, True)

    def on_close(self):
        self.send_system_info("A user has left", True)


ChatRouter = tornadio.get_router(ChatParticipant, resource='chat')
ClockRouter = tornadio.get_router(ClockConnection, resource='clock')

application = Application(
    [
        (r"/", MainHandler),
        ChatRouter.route(),
        ClockRouter.route(),
    ],
    template_path=LOCAL_FILE('views'),
    static_path=LOCAL_FILE('public'),
    socket_io_port=8000,
    debug=True,
)

if __name__ == "__main__":
예제 #24
0
파일: server.py 프로젝트: imclab/imolecule
    parser.add_argument("--debug", action="store_true", help="Prints all "
                        "transmitted data streams")
    parser.add_argument("--http-port", type=int, default=8000, help="The port "
                        "on which to serve the website")
    parser.add_argument("--tcp-port", type=int, default=5000, help="The "
                        "server-side tcp connection for python-js interaction")
    args = parser.parse_args()

    HTTP_PORT, TCP_PORT = args.http_port, args.tcp_port
    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)

    with open("index.html") as index_file:
        INDEX = index_file.read() % {"port": HTTP_PORT}

    WebClientRouter = tornadio.get_router(ClientConnection)
    handler = [(r"/", IndexHandler), WebClientRouter.route(),
               (r'/static/(.*)', tornado.web.StaticFileHandler,
                {'path': ROOT})]
    kwargs = {"enabled_protocols": ["websocket"],
              "socket_io_port": HTTP_PORT}
    application = tornado.web.Application(handler, **kwargs)

    webbrowser.open("http://localhost:%d/" % HTTP_PORT, new=2)

    context = zmq.Context()
    socket = context.socket(zmq.REP)
    socket.bind("tcp://127.0.0.1:%d" % TCP_PORT)
    stream = zmqstream.ZMQStream(socket, tornado.ioloop.IOLoop.instance())
    stream.on_recv(ClientConnection.on_message)
    tornadio.server.SocketServer(application)
    self.daemon = True;
    self.civcom = civcom;
    self.ws_connection = ws_connection;

  def run(self):
    while 1:
      if (self.civcom.stopped): return;

      packet = self.civcom.get_send_result_string();
      if (len(packet) > 4):
        self.ws_connection.send(packet);
      time.sleep(WS_UPDATE_INTERVAL);



CivRouter = tornadio.get_router(CivConnection)

application = tornado.web.Application(
    [(r"/status", IndexHandler), CivRouter.route()],
    enabled_protocols = ['websocket',
                         'flashsocket',
                         'xhr-multipart',
                         'xhr-polling'],
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port = 8002
)

if __name__ == "__main__":
    import logging
    logging.getLogger().setLevel(level=logging.INFO);
예제 #26
0
    # def on_open(self, *args, **kwargs):
    server = None
	
    def on_message(self, message):
        if message['action'] == 'connect':
            self.server = SourceRcon.SourceRcon(message['host'], message['port'], message['password'])
            self.send(json.dumps({"action": "connected"}))
        elif message['action'] == 'rcon':
            self.send(json.dumps({'action': 'rcon', 'orginalCommand': message['command'], 'output': self.server.rcon(message['command'])}))
        
    def on_close(self):
        if self.server:
            self.server.disconnect()

#use the routes classmethod to build the correct resource
RconRouter = tornadio.get_router(SourceRconConnection)

#configure the Tornado application
application = tornado.web.Application(
    [RconRouter.route()],
    enabled_protocols = ['websocket',
                         'flashsocket',
                         'xhr-multipart',
                         'xhr-polling'],
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port = 8001
)

if __name__ == "__main__":
    import logging
예제 #27
0
        for socket in CHANNELS[channel]:
            socket.send(data)
        self.write('Posted to %s subscribers' % len(CHANNELS[channel]))

    def get(self, channel):
        self._announce(channel)

    def post(self, channel):
        self._announce(channel)

class Stats(tornado.web.RequestHandler):
    def get(self, channel):
        channel = normalize_channel(channel)
        self.write('''
<html>
    <head>
    </head>
    <body>
        <b>Channel:</b> %(channel)s <br/>
        <b>Subscribers:</b> %(count)s <br/>
    </body>
</html>
        ''' % dict(channel=channel, count=len(CHANNELS.get(channel, [])))
        )

SocketIORoute = tornadio.get_router(
    SocketIOConnection, 
    resource='',
    extra_re=r'.+'
).route()
예제 #28
0
import tornado.web
from tornadio import server, get_router

from connection import ClientConnection
from handler import BroadcastHandler


urls = [ (r"/", BroadcastHandler), get_router(ClientConnection).route() ]

application = tornado.web.Application( urls )

if __name__ == "__main__":
    server.SocketServer(application)
예제 #29
0
import tornado.web
import tornadio
import tornadio.router
import tornadio.server

ROOT = op.normpath(op.dirname(__file__))

class IndexHandler(tornado.web.RequestHandler):
    """Regular HTTP handler to serve the ping page"""
    def get(self):
        return

class PingConnection(tornadio.SocketConnection):
    def on_open(self, request, *args, **kwargs):
        self.ip = request.remote_ip

    def on_message(self, message):
        self.send(message)

PingRouter = tornadio.get_router(PingConnection)

application = tornado.web.Application(
    [(r"/", IndexHandler), PingRouter.route()],
    socket_io_port = 8001,
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml')
)

if __name__ == "__main__":
    tornadio.server.SocketServer(application)
예제 #30
0
			         })
		else:
			current_status = self.get_argument('status')
			print "status:", current_status
			broadcast(current_status)
		self.write("Hello, world")


class SocketHandler(tornadio.SocketConnection):
	def on_open(self, *args, **kwargs):
		print "OPEN"
		clients.add(self)

	def on_message(self, message):
		print "MSG", message

	def on_close(self):
		print "CLOSE"
		try:
			clients.remove(self)
		except: pass

application = tornado.web.Application([
	(r'/update', MainHandler),
	tornadio.get_router(SocketHandler).route(),
])

if __name__ == '__main__':
	application.listen(5679)
	tornado.ioloop.IOLoop.instance().start()
예제 #31
0
			p.send(message)

class MainHandler(tornado.web.RequestHandler):
	def get(self):
		loader = tornado.template.Loader("/home/erik/Desktop/Projects/tornadobubbler/templates")
		self.write(loader.load("bubbler.html").generate())
		
class BubblePostHandler(tornado.web.RequestHandler):
	def post(self):
		newBubble = self.get_argument('newBub[]')
		server.send_to_everyone(newBubble)


server = BubbleServer()

MyRouter = tornadio.get_router(SIOHandler)

application = tornado.web.Application([
				#(r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "static"}),
				(r"/", MainHandler),
				(r"/a/postbubble", BubblePostHandler),
				MyRouter.route()],
				enabled_protocols = ['websocket',
								 'xhr-multipart',
								  'xhr-polling'],
						  socket_io_port = 24432,
)


if __name__ == "__main__":
예제 #32
0
                                       'y': self.y}})
        server.map.tick(server)


    def on_close(self):
        server.participants.remove(self)
        packet = {'left': {'id': self.id}}
        for p in server.participants:
            server.send(p, packet)

settings = {
    'static_path': os.path.join(os.path.dirname(__file__), 'static'),
}

#use the routes classmethod to build the correct resource
ChatRouter = tornadio.get_router(PlayerConn)

#configure the Tornado application
application = tornado.web.Application(
    [(r"/static/(.*)", tornado.web.StaticFileHandler, dict(path=settings['static_path'])), 
     (r"/", IndexHandler), 
     ChatRouter.route()],
    enabled_protocols = ['websocket',
                         'flashsocket',
                         'xhr-multipart',
                         'xhr-polling'],
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port = 8001
)
예제 #33
0
            log.error("DB exception, rolling back:\n%s" % traceback.format_exc())
            db.rollback()

        MonitorSocket.update(self.uid)
        gc.collect()

application = tornado.web.Application([
    (r"/(favicon.ico)", tornado.web.StaticFileHandler, {"path": "static/img/"}),
    (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "static/"}),
    (r"/monitor[/]?([^/]+)?[/]?(.*)", MonitorHandler), #Fix this
    (r"/upload", UploadHandler),
    (r"/share/(%s)" % config.uid_re, ShareHandler),
    (r"/download/(%s)" % config.uid_re, DownloadHandler),
    (r"/", MainHandler),
    tornadio.get_router(
        MonitorSocket,
        resource = config.monitor_resource
    ).route(),
    tornadio.get_router(
        ProgressSocket,
        resource = config.progress_resource,
        extra_re = config.uid_re,
        extra_sep = config.socket_extra_sep
    ).route()],
    socket_io_port = config.socket_io_port,
    enabled_protocols = ['websocket', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'],
    )


if __name__ == "__main__":
    Daemon()
예제 #34
0
파일: server.py 프로젝트: marxus85/oidanrot
def get_patched_router(connection, namespace, io_loop): # this fixes a regex problem appered in tornado 2.1
    router = tornadio.get_router(connection, resource=namespace, io_loop=io_loop)
    router._route = (r"/(?P<resource>%s)(?P<extra>)/(?P<protocol>%s)/?(?P<session_id>[0-9a-zA-Z]*)/?(?P<protocol_init>\d*?)(?P<xhr_path>\w*?)/?(?P<jsonp_index>\d*?)"%(namespace,("%s" % "|".join(tornadio.router.PROTOCOLS.keys()))),router)
    return router
예제 #35
0
        self.send("CONNECTED")
        global connections
        connections.add(self)
        
    def on_message(self, message):
        for p in self.participants:
            p.send(message)

    def on_close(self):
        self.participants.remove(self)
        self.send("DISCONNECTED")
        global connections
        connections.remove(self)

#use the routes classmethod to build the correct resource
ChatRouter = tornadio.get_router(ChatConnection)

#configure the Tornado application
application = tornado.web.Application(
    [(r"/", IndexHandler, None), ChatRouter.route()],
    enabled_protocols = ['websocket',
                         'flashsocket',
                         'xhr-multipart',
                         'xhr-polling'],
    flash_policy_port = 843,
    flash_policy_file = op.join(ROOT, 'flashpolicy.xml'),
    socket_io_port = 8001
)

if __name__ == "__main__":
    # initialize login
예제 #36
0
파일: pushServer.py 프로젝트: COMU/routeme
        print "Client Connected"
        LISTENERS.append(self)

    def on_close(self):
        LISTENERS.remove(self)

    def on_message(self, message):
        for listener in LISTENERS:
            listener.send(message)


class Announcer(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        data = self.get_argument('data')
        for socket in LISTENERS:
            socket.send(data)
        self.write('Posted')


application = tornado.web.Application([
    tornadio.get_router(SIOHandler,
                        resource=r'socket',
                        extra_re="(?P<path>.*)",
                        extra_sep='/').route(),
    (r"/push", Announcer),
])

if __name__ == "__main__":
    application.listen(8888)
    ioloop.IOLoop.instance().start()
예제 #37
0
        feed.feed["link"] = "http://pkt.li/banks/rss"

        # Create items and add to the feed
        for item in rss_items:
            feed.items.append(item)

        # Print the feed to stdout in various formats
        self.content_type = 'application/atom+xml'
        self.write(feed.format_atom_string())


if __name__ == '__main__':
    settings = {
        'template_path': os.path.join(os.path.dirname(__file__), 'templates'),
        'static_path': os.path.join(os.path.dirname(__file__), 'static'),
    }
    FIStatusRouter = tornadio.get_router(
        FIStatusSocketConnection,
        {'enabled_protocols': ['websocket', 'xhr-multipart', 'xhr-polling']},
        resource='fistatus')
    app = tornado.web.Application([
        (r'favicon.ico', tornado.web.StaticFileHandler),
        (r'/fistatus', FIStatusHandler),
        FIStatusRouter.route(),
        (r'/rss', RSSHandler),
    ],
                                  socket_io_port=8000,
                                  debug=True,
                                  **settings)
    tornadio.server.SocketServer(app)
예제 #38
0
파일: app.py 프로젝트: AaronO/notyfire
 def init_routes(self):
     router = tornadio.get_router(self.channel_server)
     self.routes = [router.route()]
예제 #39
0
			try:
				self.proc.stdin.write(message + '\n')
				self.proc.stdin.flush()
			except IOError:
				print "IOError... broken pipe?"
				if self.procFd:
					try:
						globalLoop.remove_handler(self.procFd)  # do this early
					finally:
						self.procFd = None
				try:
					self.proc.kill()
				finally:
					self.proc = None  # TODO: inform browser
		else:
			print "unknown msg", repr(message)
	def on_close(self):
		print "CLOSE", repr(self)
		if self.procFd:
			globalLoop.remove_handler(self.procFd)
			self.procFd = None
		if self.proc:
			self.on_message('.')
			self.proc = None # leave it for gc

application = tornado.web.Application([ tornadio.get_router(SocketHandler).route() ])
application.listen(5413)

globalLoop = tornado.ioloop.IOLoop.instance()
globalLoop.start()
예제 #40
0
파일: app.py 프로젝트: pthrasher/twittergeo
    """Socket.IO handler"""

    def on_open(self, *args, **kwargs):
        global SUBSCRIBERS
        SUBSCRIBERS.append(self)

    def on_close(self):
        global SUBSCRIBERS
        if self in SUBSCRIBERS:
            SUBSCRIBERS.remove(self)


#
# URL related
#
GeoRouter = tornadio.get_router(GeoHandler)
urls = [(r"/", IndexHandler), GeoRouter.route()]

#
# App settings
#
settings = {
    "enabled_protocols": ["websocket", "flashsocket", "xhr-multipart", "xhr-polling"],
    "socket_io_port": os.environ.get("PORT", 80),
    "socket_io_address": "0.0.0.0",
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
}


if __name__ == "__main__":
    application = tornado.web.Application(urls, **settings)