Building apps using Flask-SocketIO and JavaScript Socket.IO (Intro)
I have been avoiding sockets for quite some time now. When asked to build small chat applications I (to save myself trouble of learning about sockets) I deferred the task or in worst cases resorted to cheap tricks like infinitely reloading back-end scripts written in PHP/Node.js,/Flask and some asynchronous magic using Ajax. I hated myself every time I did that, because to be honest I was developing a low quality product which wasn’t scalable. So finally I built up the courage to tackle the devil and settle this issue once and for all.
Introduction to WebSockets.
WebSocket was introduced in HTML5 to ease the communication between clients and server. A WebSocket connection is a persistent, bi-directional communication channel between a client and the server.
WebSocket connections are specially useful in low latency conditions.
To be able to build a web application using sockets, socket must implemented on both server and client level. Hence I needed to choose a back-end language and front-end language with a suitable implementation of sockets, I landed up with SocketIO (JavaScript) and Flask-Sockets (Python) for front-end and back-end respectively.
What is SocketIO?
SocketIO is a cross-browser Javascript library that abstracts the client application from the actual transport protocol. For modern browsers the WebSocket protocol is used, but for older browsers that don’t have WebSocket SocketIO emulates the connection using one of the older solutions, the best one available for each given client.
// Establishing connection with the server hosted at domain:port
var socket = io.connect('http://domain:port');
// Listening for event named `any event`
socket.on('any event', function(msg) {
console.log(msg);
});
The code to get sockets working in JS is pretty basic as can be seen in the example above.
What about Flask-Sockets?
Flask-SocketIO creates an environment for event handlers that is close to that of regular view functions, including the creation of application and request contexts. Lets look at some of operations that can be done using flask-sockets.
Initialization.
#A bunch of import statements which you should ignore for now
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
if __name__ == '__main__':
socketio.run(app)
Receiving messages from client.
@socketio.on('message')
def handle_message(message):
print('received message: ' + message)
Sending messages to client.
from flask_socketio import send, emit
@socketio.on('my event')
def handle_my_custom_event(json):
emit('my response', json)
The plan ahead.
To fully grasp the concept I decided to divide the process into segments so as to make the task simple. I planned on building 4 apps using sockets.
Learn basics of sockets by building a range slider, that will be synchronized across multiple clients.
Learning concepts of namespaces and sessions in sockets by building a 1–1 chat app.
Explore rooms in sockets , while building a chat room app.
A bonus app, that I will decide as I develop clearer understanding of sockets.
As final advice .