Websockets are a very interesting new type of technology, they allow a multitude of different things for developers to be able to do with sites and apps such as: giving clients the ability to talk to one another in real time, showing the live score of a gaming match, and even sending traffic updates. The core feature of what makes Websockets so great is that it is used to broadcast information via a client and a server. the server often times recieves information and relays said information over to the client(s) for them to be able to view. If you've ever watched a live stream from tiktok you've witnessed websockets in action. Websockets uses what is called Full duplex bi directional Communication between the client and server which really just means the client and server speak to each other in real time without having to initiate a new request. I like to relate it to a page that is justs continous with it's chat feature, none of the old datat is deleted, and a new client can come in and join and create new data and see the old data being displayed. Here I'm going to display some code using SocketIO, Flask, Javascript & Python.
To set up the SocketIO server we first want to follow these steps.
after importing flask, flask socketio and flask cors, I'm creating a flask instance with app = Flask(name)
app = Flask(name)
after which I'm adding a secret key for my Flask application this will help secure sessions and sign cookies for future use.
app.config['SECRET_KEY'] = "secret!"
Adding CORS (Cross Origin Resource Sharing) allows my routes to be accessed from any origin.
CORS(app, resources={r"/":{"origins":""}})
Here I'm initializing Flask-SocketIO to go and enable the bi directional communication we discussed before, the inner portion (app, cors_allowed_origins="*") is allowing connections from any origin much like how the previous CORS does.
socketio = SocketIO(app, cors_allowed_origins="*")
Our next step is to define a route in our flask application that will handle our HTTP request sent to our URL path.
@app.route('/http-call')
def http_call():
data = {'data':'text fetched via an HTTP Call to server on render'}
return jsonify(data)
When a client sends a request to our localhost3000/http-call we'll invoke this above function.
@socketio.on('connect')
def connected():
print(request.sid)
print("Client is connected")
Here we created a function that listens for the connect event in our Flask-SocketIO app. Once a new client connects with a websocket to our server our above function is executed and prints a response informing our chat feed that someone new has connected.
@socketio.on('disconnect')
def disconnected():
print("User disconnected")
emit("disconnect", f"user {request.sid} has been disconnected", broadcast=True)
our second function here is our disconnect function that informs our chat that the user has disconnected once their websocket is no longer active.
@socketio.on('data')
def handle_message(data):
print("Data from the front end: ",str(data))
emit("data",{
'data': data, 'id':request.sid
}, broadcast=True)
our last function sends information to our client side. Here we are emitting data back to all our connected clients including the person who sent their message. Here we pass in broadcast=True as the unique argument to ensure the message is sent to all of our connected clients. our request.sid is sent with our event. I do want to note that the request.sid works almost like a social security number as it serves as the unique ID of the client that is sending the message.
Top comments (0)