tornadio2.conn
¶
Connection¶
tornadio2.conn¶
Tornadio connection implementation.
-
class
tornadio2.conn.
SocketConnection
(session, endpoint=None)[source]¶ Subclass this class and define at least on_message() method to make a Socket.IO connection handler.
To support socket.io connection multiplexing, define _endpoints_ dictionary on class level, where key is endpoint name and value is connection class:
class MyConnection(SocketConnection): __endpoints__ = {'/clock'=ClockConnection, '/game'=GameConnection}
ClockConnection
andGameConnection
should derive from theSocketConnection
class as well.SocketConnection
has usefulevent
decorator. Wrap method with it:class MyConnection(SocketConnection): @event('test') def test(self, msg): print msg
and then, when client will emit ‘test’ event, you should see ‘Hello World’ printed:
sock.emit('test', {msg:'Hello World'});
Callbacks¶
-
SocketConnection.
on_open
(request)[source]¶ Default on_open() handler.
Override when you need to do some initialization or request validation. If you return False, connection will be rejected.
You can also throw Tornado HTTPError to close connection.
- request
ConnectionInfo
object which contains caller IP address, query string parameters and cookies associated with this request.
For example:
class MyConnection(SocketConnection): def on_open(self, request): self.user_id = request.get_argument('id', None) if not self.user_id: return False
-
SocketConnection.
on_message
(message)[source]¶ Default on_message handler. Must be overridden in your application
-
SocketConnection.
on_event
(name, args=[], kwargs={})[source]¶ Default on_event handler.
By default, it uses decorator-based approach to handle events, but you can override it to implement custom event handling.
- name
- Event name
- args
- Event args
- kwargs
- Event kwargs
There’s small magic around event handling. If you send exactly one parameter from the client side and it is dict, then you will receive parameters in dict in kwargs. In all other cases you will have args list.
For example, if you emit event like this on client-side:
sock.emit('test', {msg='Hello World'})
you will have following parameter values in your on_event callback:
name = 'test' args = [] kwargs = {msg: 'Hello World'}
However, if you emit event like this:
sock.emit('test', 'a', 'b', {msg='Hello World'})
you will have following parameter values:
name = 'test' args = ['a', 'b', {msg: 'Hello World'}] kwargs = {}
Output¶
-
SocketConnection.
send
(message, callback=None, force_json=False)[source]¶ Send message to the client.
- message
- Message to send.
- callback
- Optional callback. If passed, callback will be called when client received sent message and sent acknowledgment back.
- force_json
- Optional argument. If set to True (and message is a string) then the message type will be JSON (Type 4 in socket_io protocol). This is what you want, when you send already json encoded strings.