Exemplo n.º 1
0
def setup_socketio(app: web.Application):

    # SEE https://github.com/miguelgrinberg/python-socketio/blob/v4.6.1/docs/server.rst#aiohttp
    # TODO: ujson to speed up?
    # TODO: client_manager= to socketio.AsyncRedisManager/AsyncAioPikaManager for horizontal scaling (shared sessions)
    sio = AsyncServer(async_mode="aiohttp", logger=log, engineio_logger=False)
    sio.attach(app)

    app[APP_CLIENT_SOCKET_SERVER_KEY] = sio
    handlers_utils.register_handlers(app, handlers)
Exemplo n.º 2
0
def setup_socketio(app: web.Application):
    # ----------------------------------------------
    # TODO: temporary, just to check compatibility between
    # trafaret and pydantic schemas
    assert_valid_config(app)
    # ---------------------------------------------
    mgr = None
    sio = AsyncServer(async_mode="aiohttp", client_manager=mgr, logging=log)
    sio.attach(app)
    app[APP_CLIENT_SOCKET_SERVER_KEY] = sio
    handlers_utils.register_handlers(app, handlers)
Exemplo n.º 3
0
    def aiohttp_server(self):
        sio = AsyncServer(async_mode="aiohttp")

        @sio.on(EVENT_USER_UTTERED)
        async def on_user_uttered(session_id: str, request: Any):
            if self.bot_messages_stack:
                messages = self.bot_messages_stack.pop(0)
                for message in messages:
                    await sio.emit(EVENT_BOT_UTTERED, message, room=session_id)

        app = web.Application()
        sio.attach(app)
        runner = web.AppRunner(app)
        return runner
Exemplo n.º 4
0
async def api_server(
        game_app: game.GameApp, sio: AsyncServer,
        player_ranking_repository: PlayerRankingRepository) -> web.AppRunner:
    app = web.Application()
    sio.attach(app)

    logging.basicConfig(level=logging.DEBUG)
    setup_routes(app, sio, game_app, player_ranking_repository)

    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, "0.0.0.0", 8080)
    await site.start()
    return runner
Exemplo n.º 5
0
    async def start(self):
        global sio
        sio = AsyncServer(async_mode='aiohttp')
        self.sio = sio

        @sio.event
        async def connect(sid, environ):
            global client_sid
            client_sid = sid
            await sio.emit('response', {'type': 'response'})

        self.enable_sync()
        sio.attach(self.app, socketio_path='ws')
        self.runner = web.AppRunner(self.app)
        await self.runner.setup()
        site = web.TCPSite(self.runner, 'localhost', 8080)
        await site.start()
Exemplo n.º 6
0
    def run(self):
        global sio
        global app

        if sio:
            return

        sio = AsyncServer(async_mode='sanic',
                          cors_allowed_origins=[],
                          allow_upgrades=True,
                          transports=['websocket'],
                          ping_interval=15,
                          ping_timeout=25,
                          engineio_logger=False)
        app = Sanic()
        sio.attach(app)

        @sio.on('funenc_socketio_client_msg')
        def mdias_event(sid, data):
            _logger.debug(
                "get mdias msg: {data} with sid {sid}".format(data=data, sid=sid))
            return model_env.deal_event(sid, data)

        @sio.event
        async def connect(sid, environ):
            return model_env.deal_user_connect(sid, environ)

        @sio.event
        async def disconnect(sid):
            model_env.deal_user_disconnect(sid)

        # 必需放在服务线程中, 否则会报utf8错误
        threading.Thread(target=self.start_client_event).start()
        port = 9080
        app.config['CORS_SUPPORTS_CREDENTIALS'] = True
        host = config['socket_io_host'] or '0.0.0.0'
        app.run(host=host, port=port, register_sys_signals=False)
Exemplo n.º 7
0
    'VOL-R-L': 'i',
    'VOL-R-R': 'o'
}

import asyncio
from sanic import Sanic
from sanic_jinja2 import SanicJinja2
from socketio import AsyncServer
from datetime import datetime
from time import mktime
import pyautogui
pyautogui.FAILSAFE = False

sio = AsyncServer(async_mode='sanic')
app = Sanic(__name__)
sio.attach(app)
jinja = SanicJinja2(app)


def millis_interval(start, end):
    """start and end are datetime instances"""
    diff = end - start
    millis = diff.days * 24 * 60 * 60 * 1000
    millis += diff.seconds * 1000
    millis += diff.microseconds / 1000
    return millis


@app.route('/')
@jinja.template('index.html')
async def index(request):
Exemplo n.º 8
0
def setup(app: web.Application):
    mgr = None
    sio = AsyncServer(async_mode="aiohttp", client_manager=mgr, logging=log)
    sio.attach(app)
    app[APP_CLIENT_SOCKET_SERVER_KEY] = sio
    handlers_utils.register_handlers(app, handlers)
Exemplo n.º 9
0
def main():

    args = docopt(usage, version="Adapter 0.1")

    sio = AsyncServer()
    app = web.Application()
    sio.attach(app)

    # start engine

    try:

        proc = subprocess.Popen([args["<engine>"]],
                                stdout=subprocess.PIPE,
                                stdin=subprocess.PIPE,
                                stderr=subprocess.STDOUT,
                                universal_newlines=True,
                                bufsize=1)

    except OSError as exp:

        msg = "Could not start engine: %s" % args["<engine>"]
        raise Exception(msg)

    # define message handler

    @sio.on('msg')
    async def handle_message(sid, data):

        # log message and send to engine

        req_str = json.dumps(data)
        log_event(sid, req_str, "green")
        proc.stdin.write("%s\n" % req_str)

        # read, log and parse engine output

        try:

            unfinished = True

            while unfinished:
                rep_str = proc.stdout.readline().strip()
                response = json.loads(rep_str)
                unfinished = response.get("result") not in ["success", "error"]
                color = "yellow" if unfinished else "cyan"
                log_event(sid, rep_str, color)
                await sio.emit('reply', response)

                # For some reason, the reply message is not sent until the
                # next await statement. As a workaround, send a dummy message.
                # TODO: fix
                await sio.emit('dummy')

        except ValueError:
            log_event(sid,
                      "Engine returned an invalid JSON string: " + rep_str,
                      "red")
            response = {
                "result": "error",
                "description": "internal engine error"
            }
            await sio.emit('reply', response)

    # start server

    web.run_app(app, port=9020)