3
ñ\ð]'†  ã               @   sf   d dl Z d dlZd dlZddlmZ ddlmZ ddlmZ ddlmZ e jdƒZ	G dd	„ d	e
ƒZdS )
é    Né   )Úbase_manager)Ú
exceptions)Ú	namespace)Úpacketzsocketio.serverc               @   s.  e Zd ZdZdGdd„Zdd„ ZdHd	d
„Zdd„ Zdd„ ZdIdd„Z	dJdd„Z
dKdd„ZdLdd„ZdMdd„ZdNdd„ZdOdd„ZdPdd„ZdQd d!„ZdRd"d#„ZdSd$d%„Zd&d'„ Zd(d)„ Zd*d+„ ZdTd-d.„ZdUd/d0„Zd1d2„ Zd3d4„ Zd5d6„ Zd7d8„ Zd9d:„ Zd;d<„ Zd=d>„ Zd?d@„ Z dAdB„ Z!dCdD„ Z"dEdF„ Z#dS )VÚServera  A Socket.IO server.

    This class implements a fully compliant Socket.IO web server with support
    for websocket and long-polling transports.

    :param client_manager: The client manager instance that will manage the
                           client list. When this is omitted, the client list
                           is stored in an in-memory structure, so the use of
                           multiple connected servers is not possible.
    :param logger: To enable logging set to ``True`` or pass a logger object to
                   use. To disable logging set to ``False``. The default is
                   ``False``.
    :param binary: ``True`` to support binary payloads, ``False`` to treat all
                   payloads as text. On Python 2, if this is set to ``True``,
                   ``unicode`` values are treated as text, and ``str`` and
                   ``bytes`` values are treated as binary.  This option has no
                   effect on Python 3, where text and binary payloads are
                   always automatically discovered.
    :param json: An alternative json module to use for encoding and decoding
                 packets. Custom json modules must have ``dumps`` and ``loads``
                 functions that are compatible with the standard library
                 versions.
    :param async_handlers: If set to ``True``, event handlers for a client are
                           executed in separate threads. To run handlers for a
                           client synchronously, set to ``False``. The default
                           is ``True``.
    :param always_connect: When set to ``False``, new connections are
                           provisory until the connect handler returns
                           something other than ``False``, at which point they
                           are accepted. When set to ``True``, connections are
                           immediately accepted, and then if the connect
                           handler returns ``False`` a disconnect is issued.
                           Set to ``True`` if you need to emit events from the
                           connect handler and your client is confused when it
                           receives events before the connection acceptance.
                           In any other case use the default of ``False``.
    :param kwargs: Connection parameters for the underlying Engine.IO server.

    The Engine.IO configuration supports the following settings:

    :param async_mode: The asynchronous model to use. See the Deployment
                       section in the documentation for a description of the
                       available options. Valid async modes are "threading",
                       "eventlet", "gevent" and "gevent_uwsgi". If this
                       argument is not given, "eventlet" is tried first, then
                       "gevent_uwsgi", then "gevent", and finally "threading".
                       The first async mode that has all its dependencies
                       installed is then one that is chosen.
    :param ping_timeout: The time in seconds that the client waits for the
                         server to respond before disconnecting. The default
                         is 60 seconds.
    :param ping_interval: The interval in seconds at which the client pings
                          the server. The default is 25 seconds.
    :param max_http_buffer_size: The maximum size of a message when using the
                                 polling transport. The default is 100,000,000
                                 bytes.
    :param allow_upgrades: Whether to allow transport upgrades or not. The
                           default is ``True``.
    :param http_compression: Whether to compress packages when using the
                             polling transport. The default is ``True``.
    :param compression_threshold: Only compress messages when their byte size
                                  is greater than this value. The default is
                                  1024 bytes.
    :param cookie: Name of the HTTP cookie that contains the client session
                   id. If set to ``None``, a cookie is not sent to the client.
                   The default is ``'io'``.
    :param cors_allowed_origins: Origin or list of origins that are allowed to
                                 connect to this server. Only the same origin
                                 is allowed by default. Set this argument to
                                 ``'*'`` to allow all origins, or to ``[]`` to
                                 disable CORS handling.
    :param cors_credentials: Whether credentials (cookies, authentication) are
                             allowed in requests to this server. The default is
                             ``True``.
    :param monitor_clients: If set to ``True``, a background task will ensure
                            inactive clients are closed. Set to ``False`` to
                            disable the monitoring task (not recommended). The
                            default is ``True``.
    :param engineio_logger: To enable Engine.IO logging set to ``True`` or pass
                            a logger object to use. To disable logging set to
                            ``False``. The default is ``False``.
    NFTc       
      K   sF  |}|j dd ƒ}	|	d k	r |	|d< |d k	r8|tj_||d< d|d< | jƒ f |Ž| _| jjd| jƒ | jjd| jƒ | jjd| j	ƒ || _
i | _i | _i | _i | _t|tƒs°|| _nRt| _tjj oÌ| jjtjk�r|rä| jjtjƒ n| jjtjƒ | jjtjƒ ƒ |d k�rtjƒ }|| _| jj| ƒ d| _ || _!|| _"| jj#| _#d S )	NÚengineio_loggerÚloggerÚjsonFÚasync_handlersÚconnectÚmessageÚ
disconnect)$Úpopr   ÚPacketr
   Ú_engineio_server_classÚeioÚonÚ_handle_eio_connectÚ_handle_eio_messageÚ_handle_eio_disconnectÚbinaryÚenvironÚhandlersÚnamespace_handlersÚ_binary_packetÚ
isinstanceÚboolr	   Údefault_loggerÚloggingÚrootÚlevelÚNOTSETÚsetLevelÚINFOÚERRORÚ
addHandlerÚStreamHandlerr   ZBaseManagerÚmanagerZ
set_serverÚmanager_initializedr   Úalways_connectZ
async_mode)
ÚselfZclient_managerr	   r   r
   r   r*   ÚkwargsZengineio_optionsr   © r-   ú:/tmp/pip-build-mqc4i71p/python-socketio/socketio/server.pyÚ__init__a   sD    


zServer.__init__c             C   s   dS )NFr-   )r+   r-   r-   r.   Úis_asyncio_based�   s    zServer.is_asyncio_basedc                s0   ˆpd‰‡ ‡‡fdd„}|dkr$|S ||ƒ dS )aù  Register an event handler.

        :param event: The event name. It can be any string. The event names
                      ``'connect'``, ``'message'`` and ``'disconnect'`` are
                      reserved and should not be used.
        :param handler: The function that should be invoked to handle the
                        event. When this parameter is not given, the method
                        acts as a decorator for the handler function.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the handler is associated with
                          the default namespace.

        Example usage::

            # as a decorator:
            @socket_io.on('connect', namespace='/chat')
            def connect_handler(sid, environ):
                print('Connection request')
                if environ['REMOTE_ADDR'] in blacklisted:
                    return False  # reject

            # as a method:
            def message_handler(sid, msg):
                print('Received message: ', msg)
                eio.send(sid, 'response')
            socket_io.on('message', namespace='/chat', message_handler)

        The handler function receives the ``sid`` (session ID) for the
        client as first argument. The ``'connect'`` event handler receives the
        WSGI environment as a second argument, and can return ``False`` to
        reject the connection. The ``'message'`` handler and handlers for
        custom event names receive the message payload as a second argument.
        Any values returned from a message handler will be passed to the
        client's acknowledgement callback function if it exists. The
        ``'disconnect'`` handler does not take a second argument.
        ú/c                s&   ˆˆj kri ˆj ˆ< | ˆj ˆ ˆ < | S )N)r   )Úhandler)Úeventr   r+   r-   r.   Úset_handler¹   s    

zServer.on.<locals>.set_handlerNr-   )r+   r3   r2   r   r4   r-   )r3   r   r+   r.   r   ’   s
    %z	Server.onc                sT   t ˆ ƒdkr<t ˆƒdkr<tˆ d ƒr<ˆjˆ d jƒˆ d ƒS ‡ ‡‡fdd„}|S dS )a�  Decorator to register an event handler.

        This is a simplified version of the ``on()`` method that takes the
        event name from the decorated function.

        Example usage::

            @sio.event
            def my_event(data):
                print('Received data: ', data)

        The above example is equivalent to::

            @sio.on('my_event')
            def my_event(data):
                print('Received data: ', data)

        A custom namespace can be given as an argument to the decorator::

            @sio.event(namespace='/test')
            def my_event(data):
                print('Received data: ', data)
        r   r   c                s   ˆj | jfˆ žˆŽ| ƒS )N)r   Ú__name__)r2   )Úargsr,   r+   r-   r.   r4   á   s    z!Server.event.<locals>.set_handlerN)ÚlenÚcallabler   r5   )r+   r6   r,   r4   r-   )r6   r,   r+   r.   r3   Ã   s    $zServer.eventc             C   sF   t |tjƒstdƒ‚| jƒ |jƒ kr,tdƒ‚|j| ƒ || j|j< dS )zõRegister a namespace handler object.

        :param namespace_handler: An instance of a :class:`Namespace`
                                  subclass that handles all the event traffic
                                  for a namespace.
        zNot a namespace instancez+Not a valid namespace class for this serverN)r   r   Ú	NamespaceÚ
ValueErrorr0   Z_set_serverr   )r+   Únamespace_handlerr-   r-   r.   Úregister_namespaceæ   s    
zServer.register_namespacec       	      K   sJ   |pd}|p|}| j jd||p d|ƒ | jj|||f|||dœ|—Ž dS )a÷  Emit a custom event to one or more connected clients.

        :param event: The event name. It can be any string. The event names
                      ``'connect'``, ``'message'`` and ``'disconnect'`` are
                      reserved and should not be used.
        :param data: The data to send to the client or clients. Data can be of
                     type ``str``, ``bytes``, ``list`` or ``dict``. If a
                     ``list`` or ``dict``, the data will be serialized as JSON.
        :param to: The recipient of the message. This can be set to the
                   session ID of a client to address only that client, or to
                   to any custom room created by the application to address all
                   the clients in that room, If this argument is omitted the
                   event is broadcasted to all connected clients.
        :param room: Alias for the ``to`` parameter.
        :param skip_sid: The session ID of a client to skip when broadcasting
                         to a room or to all clients. This can be used to
                         prevent a message from being sent to the sender. To
                         skip multiple sids, pass a list.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the event is emitted to the
                          default namespace.
        :param callback: If given, this function will be called to acknowledge
                         the the client has received the message. The arguments
                         that will be passed to the function are those provided
                         by the client. Callback functions can only be used
                         when addressing an individual client.
        :param ignore_queue: Only used when a message queue is configured. If
                             set to ``True``, the event is emitted to the
                             clients directly, without going through the queue.
                             This is more efficient, but only works when a
                             single server process is used. It is recommended
                             to always leave this parameter with its default
                             value of ``False``.
        r1   zemitting event "%s" to %s [%s]Úall)ÚroomÚskip_sidÚcallbackN)r	   Úinfor(   Úemit)	r+   r3   ÚdataÚtor>   r?   r   r@   r,   r-   r-   r.   rB   õ   s    $
zServer.emitc          	   K   s"   | j d||||||dœ|—Ž dS )aœ  Send a message to one or more connected clients.

        This function emits an event with the name ``'message'``. Use
        :func:`emit` to issue custom event names.

        :param data: The data to send to the client or clients. Data can be of
                     type ``str``, ``bytes``, ``list`` or ``dict``. If a
                     ``list`` or ``dict``, the data will be serialized as JSON.
        :param to: The recipient of the message. This can be set to the
                   session ID of a client to address only that client, or to
                   to any custom room created by the application to address all
                   the clients in that room, If this argument is omitted the
                   event is broadcasted to all connected clients.
        :param room: Alias for the ``to`` parameter.
        :param skip_sid: The session ID of a client to skip when broadcasting
                         to a room or to all clients. This can be used to
                         prevent a message from being sent to the sender. To
                         skip multiple sids, pass a list.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the event is emitted to the
                          default namespace.
        :param callback: If given, this function will be called to acknowledge
                         the the client has received the message. The arguments
                         that will be passed to the function are those provided
                         by the client. Callback functions can only be used
                         when addressing an individual client.
        :param ignore_queue: Only used when a message queue is configured. If
                             set to ``True``, the event is emitted to the
                             clients directly, without going through the queue.
                             This is more efficient, but only works when a
                             single server process is used. It is recommended
                             to always leave this parameter with its default
                             value of ``False``.
        r   )rC   rD   r>   r?   r   r@   N)r   )rB   )r+   rC   rD   r>   r?   r   r@   r,   r-   r-   r.   Úsend   s    $zServer.sendé<   c       	         s–   | j stdƒ‚| jjƒ ‰g ‰ ‡ ‡fdd„}| j|f||p:|||dœ|—Ž ˆj|d�s^tjƒ ‚tˆ d ƒdkrvˆ d S tˆ d ƒdkr’ˆ d d S dS )	aö  Emit a custom event to a client and wait for the response.

        :param event: The event name. It can be any string. The event names
                      ``'connect'``, ``'message'`` and ``'disconnect'`` are
                      reserved and should not be used.
        :param data: The data to send to the client or clients. Data can be of
                     type ``str``, ``bytes``, ``list`` or ``dict``. If a
                     ``list`` or ``dict``, the data will be serialized as JSON.
        :param to: The session ID of the recipient client.
        :param sid: Alias for the ``to`` parameter.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the event is emitted to the
                          default namespace.
        :param timeout: The waiting timeout. If the timeout is reached before
                        the client acknowledges the event, then a
                        ``TimeoutError`` exception is raised.
        :param ignore_queue: Only used when a message queue is configured. If
                             set to ``True``, the event is emitted to the
                             client directly, without going through the queue.
                             This is more efficient, but only works when a
                             single server process is used. It is recommended
                             to always leave this parameter with its default
                             value of ``False``.
        z/Cannot use call() when async_handlers is False.c                 s   ˆ j | ƒ ˆjƒ  d S )N)ÚappendÚset)r6   )Úcallback_argsÚcallback_eventr-   r.   Úevent_callbackg  s    
z#Server.call.<locals>.event_callback)rC   r>   r   r@   )Útimeoutr   r   N)	r   ÚRuntimeErrorr   Zcreate_eventrB   Úwaitr   ÚTimeoutErrorr7   )	r+   r3   rC   rD   Úsidr   rL   r,   rK   r-   )rI   rJ   r.   ÚcallG  s    
zServer.callc             C   s.   |pd}| j jd|||ƒ | jj|||ƒ dS )aÑ  Enter a room.

        This function adds the client to a room. The :func:`emit` and
        :func:`send` functions can optionally broadcast events to all the
        clients in a room.

        :param sid: Session ID of the client.
        :param room: Room name. If the room does not exist it is created.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the default namespace is used.
        r1   z%s is entering room %s [%s]N)r	   rA   r(   Ú
enter_room)r+   rP   r>   r   r-   r-   r.   rR   s  s    zServer.enter_roomc             C   s.   |pd}| j jd|||ƒ | jj|||ƒ dS )a2  Leave a room.

        This function removes the client from a room.

        :param sid: Session ID of the client.
        :param room: Room name.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the default namespace is used.
        r1   z%s is leaving room %s [%s]N)r	   rA   r(   Ú
leave_room)r+   rP   r>   r   r-   r-   r.   rS   ƒ  s    
zServer.leave_roomc             C   s*   |pd}| j jd||ƒ | jj||ƒ dS )a  Close a room.

        This function removes all the clients from the given room.

        :param room: Room name.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the default namespace is used.
        r1   zroom %s is closing [%s]N)r	   rA   r(   Ú
close_room)r+   r>   r   r-   r-   r.   rT   ‘  s    	zServer.close_roomc             C   s   |pd}| j j||ƒS )zîReturn the rooms a client is in.

        :param sid: Session ID of the client.
        :param namespace: The Socket.IO namespace for the event. If this
                          argument is omitted the default namespace is used.
        r1   )r(   Z	get_rooms)r+   rP   r   r-   r-   r.   Úroomsž  s    zServer.roomsc             C   s    |pd}| j j|ƒ}|j|i ƒS )aË  Return the user session for a client.

        :param sid: The session id of the client.
        :param namespace: The Socket.IO namespace. If this argument is omitted
                          the default namespace is used.

        The return value is a dictionary. Modifications made to this
        dictionary are not guaranteed to be preserved unless
        ``save_session()`` is called, or when the ``session`` context manager
        is used.
        r1   )r   Úget_sessionÚ
setdefault)r+   rP   r   Úeio_sessionr-   r-   r.   rV   ¨  s    zServer.get_sessionc             C   s    |pd}| j j|ƒ}|||< dS )a  Store the user session for a client.

        :param sid: The session id of the client.
        :param session: The session dictionary.
        :param namespace: The Socket.IO namespace. If this argument is omitted
                          the default namespace is used.
        r1   N)r   rV   )r+   rP   Úsessionr   rX   r-   r-   r.   Úsave_session¸  s    zServer.save_sessionc                s"   G ‡ ‡fdd„dt ƒ}|| ˆˆ ƒS )aN  Return the user session for a client with context manager syntax.

        :param sid: The session id of the client.

        This is a context manager that returns the user session dictionary for
        the client. Any changes that are made to this dictionary inside the
        context manager block are saved back to the session. Example usage::

            @sio.on('connect')
            def on_connect(sid, environ):
                username = authenticate_user(environ)
                if not username:
                    return False
                with sio.session(sid) as session:
                    session['username'] = username

            @sio.on('message')
            def on_message(sid, msg):
                with sio.session(sid) as session:
                    print('received message from ', session['username'])
        c                   s0   e Zd Zdd„ Z‡ ‡fdd„Z‡ ‡fdd„ZdS )z0Server.session.<locals>._session_context_managerc             S   s   || _ || _|| _d | _d S )N)ÚserverrP   r   rY   )r+   r[   rP   r   r-   r-   r.   r/   Û  s    z9Server.session.<locals>._session_context_manager.__init__c                s   | j jˆˆ d�| _| jS )N)r   )r[   rV   rY   )r+   )r   rP   r-   r.   Ú	__enter__á  s    
z:Server.session.<locals>._session_context_manager.__enter__c                s   | j jˆ| jˆ d� d S )N)r   )r[   rZ   rY   )r+   r6   )r   rP   r-   r.   Ú__exit__æ  s    z9Server.session.<locals>._session_context_manager.__exit__N)r5   Ú
__module__Ú__qualname__r/   r\   r]   r-   )r   rP   r-   r.   Ú_session_context_managerÚ  s   r`   )Úobject)r+   rP   r   r`   r-   )r   rP   r.   rY   Ä  s    zServer.sessionc             C   s†   |pd}| j j||d�r‚| jjd||ƒ | j j||d� | j|tjtj|d�ƒ | j	d||ƒ | j j
||d� |dkr‚| jj
|ƒ dS )zâDisconnect a client.

        :param sid: Session ID of the client.
        :param namespace: The Socket.IO namespace to disconnect. If this
                          argument is omitted the default namespace is used.
        r1   )r   zDisconnecting %s [%s]r   N)r(   Úis_connectedr	   rA   Úpre_disconnectÚ_send_packetr   r   Ú
DISCONNECTÚ_trigger_eventr   r   )r+   rP   r   r-   r-   r.   r   ì  s    
zServer.disconnectc             C   s   | j j|ƒS )z×Return the name of the transport used by the client.

        The two possible values returned by this function are ``'polling'``
        and ``'websocket'``.

        :param sid: The session of the client.
        )r   Ú	transport)r+   rP   r-   r-   r.   rg   þ  s    zServer.transportc             C   s   | j j||ƒS )a+  Handle an HTTP request from the client.

        This is the entry point of the Socket.IO application, using the same
        interface as a WSGI application. For the typical usage, this function
        is invoked by the :class:`Middleware` instance, but it can be invoked
        directly when the middleware is not used.

        :param environ: The WSGI environment.
        :param start_response: The WSGI ``start_response`` function.

        This function returns the HTTP response body to deliver to the client
        as a byte sequence.
        )r   Úhandle_request)r+   r   Zstart_responser-   r-   r.   rh     s    zServer.handle_requestc             O   s   | j j|f|ž|ŽS )ad  Start a background task using the appropriate async model.

        This is a utility function that applications can use to start a
        background task using the method that is compatible with the
        selected async mode.

        :param target: the target function to execute.
        :param args: arguments to pass to the function.
        :param kwargs: keyword arguments to pass to the function.

        This function returns an object compatible with the `Thread` class in
        the Python standard library. The `start()` method on this object is
        already called by this function.
        )r   Ústart_background_task)r+   Útargetr6   r,   r-   r-   r.   ri     s    zServer.start_background_taskr   c             C   s   | j j|ƒS )a  Sleep for the requested amount of time using the appropriate async
        model.

        This is a utility function that applications can use to put a task to
        sleep without having to worry about using the correct call for the
        selected async mode.
        )r   Úsleep)r+   Úsecondsr-   r-   r.   rk   )  s    zServer.sleepc          	   C   sZ   t jr| j rd}nd}t|tƒr,t|ƒ}n|g}| j|tjtj	||g| ||d�ƒ dS )zSend a message to a client.FN)r   rC   Úidr   )
ÚsixÚPY2r   r   ÚtupleÚlistrd   r   r   ÚEVENT)r+   rP   r3   rC   r   rm   r   r-   r-   r.   Ú_emit_internal3  s    


zServer._emit_internalc             C   sR   |j ƒ }t|tƒr<d}x6|D ]}| jj|||d� d}qW n| jj||dd� dS )z$Send a Socket.IO packet to a client.F)r   TN)Úencoder   rq   r   rE   )r+   rP   ÚpktÚencoded_packetr   Úepr-   r-   r.   rd   C  s    


zServer._send_packetc             C   s  |pd}| j j||ƒ | jr4| j|tjtj|d�ƒ d}y| jd||| j| ƒ}W n. t	j
k
r€ } z|j}d}W Y dd}~X nX |dkrú| jr¸| j j||ƒ | j|tjtj||d�ƒ | j j||ƒ | jsæ| j|tjtj||d�ƒ || jkrø| j|= n | j�s| j|tjtj|d�ƒ dS )z#Handle a client connection request.r1   )r   Nr   F)rC   r   )r(   r   r*   rd   r   r   ÚCONNECTrf   r   r   ÚConnectionRefusedErrorZ
error_argsrc   re   r   r%   )r+   rP   r   Zfail_reasonÚsuccessÚexcr-   r-   r.   Ú_handle_connectN  s4    





zServer._handle_connectc             C   sœ   |pd}|dkr t | jjƒ ƒ}n|g}x>|D ]6}|dkr,| jj||ƒr,| jd||ƒ | jj||ƒ q,W |dkr˜| jj||ƒr˜| jdd|ƒ | jj|dƒ dS )zHandle a client disconnect.r1   r   N)rq   r(   Zget_namespacesrb   rf   r   )r+   rP   r   Znamespace_listÚnr-   r-   r.   Ú_handle_disconnectl  s    
zServer._handle_disconnectc             C   st   |pd}| j jd|d ||ƒ | jj||ƒs@| j jd||ƒ dS | jr^| j| j| ||||ƒ n| j| ||||ƒ dS )z Handle an incoming client event.r1   z received event "%s" from %s [%s]r   z#%s is not connected to namespace %sN)r	   rA   r(   rb   Úwarningr   ri   Ú_handle_event_internal)r+   rP   r   rm   rC   r-   r-   r.   Ú_handle_event{  s    zServer._handle_eventc          	   C   sŠ   |j |d ||f|dd … žŽ }|d k	r†|d kr6g }nt|tƒrJt|ƒ}n|g}tjrd| j rdd}nd }|j|tj	tj
||||d�ƒ d S )Nr   r   F)r   rm   rC   r   )rf   r   rp   rq   rn   ro   r   rd   r   r   ÚACK)r+   r[   rP   rC   r   rm   Úrr   r-   r-   r.   r€   Š  s     

zServer._handle_event_internalc             C   s.   |pd}| j jd||ƒ | jj||||ƒ dS )z#Handle ACK packets from the client.r1   zreceived ack from %s [%s]N)r	   rA   r(   Ztrigger_callback)r+   rP   r   rm   rC   r-   r-   r.   Ú_handle_ackž  s    zServer._handle_ackc             G   sN   || j kr*|| j | kr*| j | | |Ž S || jkrJ| j| j|f|žŽ S dS )z$Invoke an application event handler.N)r   r   Ztrigger_event)r+   r3   r   r6   r-   r-   r.   rf   ¤  s
    

zServer._trigger_eventc             C   s,   | j sd| _ | jjƒ  || j|< | j|dƒS )z&Handle the Engine.IO connection event.Tr1   )r)   r(   Z
initializer   r|   )r+   rP   r   r-   r-   r.   r   ¯  s
    

zServer._handle_eio_connectc             C   s:  || j krb| j | }|j|ƒr`| j |= |jtjkrJ| j||j|j|jƒ n| j	||j|j|jƒ nÔtj
|d�}|jtjkrŠ| j||jƒ n¬|jtjkr¦| j||jƒ n�|jtjkrÊ| j||j|j|jƒ nl|jtjkrî| j	||j|j|jƒ nH|jtjk�s
|jtjk�r|| j |< n |jtjk�r.tdƒ‚ntdƒ‚dS )zDispatch Engine.IO messages.)rv   zUnexpected ERROR packet.zUnknown packet type.N)r   Úadd_attachmentZpacket_typer   ZBINARY_EVENTr�   r   rm   rC   r„   r   rx   r|   re   r~   rr   r‚   Z
BINARY_ACKr%   r:   )r+   rP   rC   ru   r-   r-   r.   r   ·  s,    



zServer._handle_eio_messagec             C   s"   | j |dƒ || jkr| j|= dS )z"Handle Engine.IO disconnect event.r1   N)r~   r   )r+   rP   r-   r-   r.   r   Ó  s    
zServer._handle_eio_disconnectc             C   s   t jS )N)Úengineior   )r+   r-   r-   r.   r   Ù  s    zServer._engineio_server_class)NFFNTF)NN)NNNNNN)NNNNN)NNNNrF   )N)N)N)N)N)N)N)N)r   )NN)$r5   r^   r_   Ú__doc__r/   r0   r   r3   r<   rB   rE   rQ   rR   rS   rT   rU   rV   rZ   rY   r   rg   rh   ri   rk   rs   rd   r|   r~   r�   r€   r„   rf   r   r   r   r   r-   r-   r-   r.   r      sJ   R 
-
1# 
* 
& 
+







(




r   )r   r†   rn   Ú r   r   r   r   Ú	getLoggerr   ra   r   r-   r-   r-   r.   Ú<module>   s   
