Usage of Flask-Soket IO

Usage of Flask-Soket IO

The internet today mostly works on HTTP Request/Response model in which the client sends a request to the server and in return the server sends a response to the client

The SocketIO can be used to establish a connection between the client and the server. The connection could be a web socket or polling. While using SocketIO, the client as well as the server receive messages as events.

The types of events are:

a.     Connect

b.     Disconnect

c.     Message

d.     JSON

e.     Custom events (provides high level flexibility)

The SocketIO upgrades a connection between a client and a server to web socket protocol which is a simultaneous, bidirectional live connection, if it’s possible otherwise it downgrades the server transparently to long polling.

The module can be used for the following tasks:

·      Receiving Messages

·      Sending Messages

·      Broadcasting

·      Creating Rooms

·      Connection Events

·      Class-Based Namespace

·      Error Handling

·      Debugging and Troubleshooting

Note: On the server side python-flask is used and on the client side Javascript callbacks are used

Let’s see the very first usage of SocketIO

Receiving Messages

To create a server-side event handler for unnamed event:

def handle_message(data):
        print(‘received message’ + data)

The above script is for text messages. It can be also used for receiving JSON data

def handle_json(json):
        print(‘received json: ’ + str(json)) 

to make this more flexible instead of defining that whether the data is a message or a JSON data simply use custom event names, and this method can also provide the facility of passing multiple arguments at once.

@socket.on(‘my event’)
def handle_custom_event(json):
        print(‘received json: ’ + str(json)) 


def handle_custom_event(arg1, arg2, arg3):
        print(‘received arguments: ’ + arg1 + arg2 + arg3) 


Sending Messages

The event handler can send messages in reply to the clients on the server by using these two functions:

-       send()

-       emit()

def handle_json(json):
        send(json, json=True)
def handle_custom_event(‘event’):
        emit(‘response’,json, namespace=’/chat)
## Events with multiple arguments can also be sent using tuples.
def handle_custom_event(‘event’):
        emit(‘response’,(‘one’, ‘two’,json), namespace=’/chat)