def server_setup(port):
    f = SockJSFactory(Factory.forProtocol(TwistedChatConnection))

    reactor.listenTCP(port, f)

    os.system('open static/index_twisted.html')

    reactor.run()
Ejemplo n.º 2
0
def run_server():
    print("Readying Reactor")
    factory = protocol.ServerFactory()
    factory.protocol = ChatProtocol
    factory.clients = []
    reactor.listenSSL(
        1025, SockJSFactory(factory, options),
        ssl.DefaultOpenSSLContextFactory(SSL_KEY_PATH, SSL_CERT_PATH))
    reactor.run()
Ejemplo n.º 3
0
 def setUp(self):
     self.site = SockJSFactory(EchoFactory())
     self.request = Request(self.path)
Ejemplo n.º 4
0
def makeService(config):
    from django.core.handlers.wsgi import WSGIHandler
    os.environ['DJANGO_SETTINGS_MODULE'] = 'lisa.server.web.weblisa.settings'

    if config['configuration']:
        ConfigManagerSingleton.get().setConfiguration(config['configuration'])

    configuration = ConfigManagerSingleton.get().getConfiguration()
    dir_path = ConfigManagerSingleton.get().getPath()

    from lisa.server import libs

    # Creating MultiService
    multi = service.MultiService()
    pool = threadpool.ThreadPool()
    tps = ThreadPoolService(pool)
    tps.setServiceParent(multi)

    # Creating the web stuff
    resource_wsgi = wsgi.WSGIResource(reactor, tps.pool, WSGIHandler())
    root = static.File('/'.join([dir_path, 'web/frontend/build']))
    backendsrc = libs.Root(resource_wsgi)
    root.putChild("backend", backendsrc)
    staticrsrc = static.File('/'.join([dir_path, 'web/interface/static']))
    root.putChild("static", staticrsrc)

    socketfactory = SockJSFactory(Factory.forProtocol(libs.WebSocketProtocol))
    root.putChild("websocket", socketfactory)

    # Configuring servers to launch
    if configuration['enable_secure_mode'] or configuration[
            'enable_unsecure_mode']:
        if configuration['enable_secure_mode']:
            SSLContextFactoryEngine = ssl.DefaultOpenSSLContextFactory(
                os.path.normpath(dir_path + '/' +
                                 'configuration/ssl/server.key'),
                os.path.normpath(dir_path + '/' +
                                 'configuration/ssl/server.crt'))
            SSLContextFactoryWeb = ssl.DefaultOpenSSLContextFactory(
                os.path.normpath(dir_path + '/' +
                                 'configuration/ssl/server.key'),
                os.path.normpath(dir_path + '/' +
                                 'configuration/ssl/server.crt'))
            ctx = SSLContextFactoryEngine.getContext()
            ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
                           libs.verifyCallback)
            # Since we have self-signed certs we have to explicitly
            # tell the server to trust them.
            with open(
                    os.path.normpath(dir_path + '/' +
                                     'configuration/ssl/server.pem'),
                    'w') as outfile:
                for file in os.listdir(
                        os.path.normpath(dir_path + '/' +
                                         'configuration/ssl/public/')):
                    with open(
                            os.path.normpath(dir_path + '/' +
                                             'configuration/ssl/public/' +
                                             file)) as infile:
                        for line in infile:
                            outfile.write(line)

            ctx.load_verify_locations(
                os.path.normpath(dir_path + '/' +
                                 'configuration/ssl/server.pem'))
            internet.SSLServer(configuration['lisa_web_port_ssl'],
                               server.Site(root),
                               SSLContextFactoryWeb).setServiceParent(multi)
            internet.SSLServer(configuration['lisa_engine_port_ssl'],
                               libs.LisaFactorySingleton.get(),
                               SSLContextFactoryEngine).setServiceParent(multi)
        if configuration['enable_unsecure_mode']:
            # Serve it up:
            internet.TCPServer(configuration['lisa_web_port'],
                               server.Site(root)).setServiceParent(multi)
            internet.TCPServer(
                configuration['lisa_engine_port'],
                libs.LisaFactorySingleton.get()).setServiceParent(multi)

        configuration['enable_cloud_mode'] = True
        #if configuration['enable_cloud_mode']:
        #    portforward.ProxyClient.dataReceived = client_dataReceived
        #    portforward.ProxyServer.dataReceived = server_dataReceived
        #    reactor.listenTCP(1080, portforward.ProxyFactory('localhost', 8000))

    else:
        exit(1)
    libs.scheduler.setServiceParent(multi)
    multi.setServiceParent(application)
    libs.Initialize()
    return multi
Ejemplo n.º 5
0
 def listen(self, protocolFactory):
     return self._endpoint.listen(
         SockJSFactory(protocolFactory, self._options))
Ejemplo n.º 6
0
    def newBullets(self):
        """
        A list of all the new bullets to be drawn
        """
        new_bullets = []
        for p in self.users:
            for b in p.new_bullets:
                new_bullets.append(b.toObj())
                b.broadcasted = True
        return new_bullets


w = WorldObjects()

f = GameFactory(w)
s = SockJSFactory(f)

#try to get the port specified, default to 8090
try:
    port = int(sys.argv[1])
except:
    port = 8090

reactor.listenTCP(port, s)

broadcast = LoopingCall(f.broadcast)
broadcast.start(0.1)

gameloop = LoopingCall(w.update)
gameloop.start(0.016666667)
Ejemplo n.º 7
0
def sockjs_server(**options):
    configure = options.get('configure', False)
    port = options.get('port', 8888)

    sockjs_options = {
        'websocket': True,
        'cookie_needed': False,
        'heartbeat': 25,
        'timeout': 5,
        'streaming_limit': 128 * 1024,
        'encoding': 'cp1252',  # Latin1
        'sockjs_url': 'https://d1fxtkz8shb9d2.cloudfront.net/sockjs-0.3.js'
    }

    zf = ZmqFactory()
    endpoint = '%s://localhost:%d' % (settings.FORWARDER_PUB_TRANSPORT,
                                      settings.FORWARDER_PUB_PORT)
    e = ZmqEndpoint("connect", endpoint)
    subscription = ZmqSubConnection(zf, e)
    # Subscripción a todos los mensajes
    subscription.subscribe("")

    class SockJSProtocol(protocol.Protocol):

        DIRECT_FORWARD_MESSAGE_TYPES = ('echo', )

        instances = []

        def __init__(self, *largs, **kwargs):
            print "SockJS"
            #protocol.Protocol.__init__(*largs, **kwargs)
            SockJSProtocol.instances.append(self)

        def dataReceived(self, data_string):
            try:
                data = json.loads(data_string)
                msgtype = data.get('type', None)
                if msgtype in self.DIRECT_FORWARD_MESSAGE_TYPES:
                    self.send_json(data, timestamp=repr(datetime.now()))
            except ValueError as e:
                print e
                self.send_json({'data': data_string, 'type': 'unknown'})

        def send_json(self, data=None, **opts):
            '''Envia una respuesta en JSON por el websocket'''
            if data:
                if isinstance(data, dict):
                    data_safe = copy(data)
                    data_safe.update(opts)
                elif isinstance(data, basestring):
                    try:
                        data_safe = json.loads(data)
                    except ValueError:
                        raise ValueError("Can't convert %s to json" % data)
            else:
                data_safe = opts
            self.transport.write(json.dumps(data_safe))

        def connectionLost(self, reason):
            print "Cerrando Socket"

            self.instances.remove(self)
            protocol.Protocol.connectionLost(self, reason)

        @classmethod
        def broadcast(cls, data, *largs, **kwargs):
            print "Received from forwarder %s" % data
            for conn in cls.instances:
                try:
                    conn.send_json(data)
                except Exception as e:
                    print e

    subscription.gotMessage = SockJSProtocol.broadcast

    factory = protocol.ServerFactory()
    factory.protocol = SockJSProtocol
    reactor.listenTCP(port, SockJSFactory(factory, sockjs_options))
    print "SocketServer running on %d" % port
    if not configure:
        try:
            reactor.run()
        except error.ReactorNotRunning:
            print "Closing bridge"
Ejemplo n.º 8
0
 def setUp(self):
     self.site = SockJSFactory(EchoFactory())