WebSocket Application Practice Guide under the Flask Framework
Abstract: WebSocket is a protocol for real-time two-way communication that can be established between a browser and a server Persistent connections. When using the Flask framework to develop web applications, combined with WebSocket, real-time data updates, instant messaging and other functions can be achieved. This article will introduce how to use WebSocket under the Flask framework and provide code examples.
Introduction:
With the development of the Internet, real-time requirements are getting higher and higher, and the traditional HTTP request-response model is no longer able to meet this demand. In the past, in order to achieve real-time communication, long polling or short polling was often used. But this method is inefficient and wastes bandwidth. The emergence of the WebSocket protocol solves this problem, allowing a persistent full-duplex connection to be established between the browser and the server to achieve real-time communication.
1. Introduction to WebSocket principle:
WebSocket protocol is a protocol based on TCP, which can establish a two-way communication channel between the browser and the server. The traditional HTTP protocol is a "request-response" model, that is, the client sends a request to the server, and the server processes the request after receiving it and returns a response to the client. The WebSocket protocol can directly establish a persistent two-way connection between the client and the server. Clients and servers can perform real-time data transfers over this connection without waiting for the same performance overhead as HTTP requests.
2. Flask integrates WebSocket:
Under the Flask framework, WebSocket support can be achieved through the Flask-SocketIO plug-in. Flask-SocketIO is an extension of the Flask framework that provides WebSocket functionality. Below are the steps to integrate WebSocket.
Install Flask-SocketIO
Install Flask-SockeIO through the pip command:
pip install flask-socketio
Import Flask-SocketIO and create an application object
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app)
Define the method of receiving WebSocket messages
@socketio.on('message') def handle_message(message): print('received message: ' + message)
Define the method of sending WebSocket messages
def send_message(message): socketio.emit('message', message)
Start Application
if __name__ == '__main__': socketio.run(app)
3. WebSocket application example:
The following is a simple chat room example to demonstrate how to use WebSocket to implement real-time chat function.
from flask import Flask, render_template from flask_socketio import SocketIO app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @socketio.on('message') def handle_message(message): socketio.emit('message', message) if __name__ == '__main__': socketio.run(app)
In index.html, you can interact with the server through JavaScript code to realize the real-time chat function.
<!DOCTYPE html> <html> <head> <title>Flask Websocket Chat</title> <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script> <script> var socket = io.connect('http://' + document.domain + ':' + location.port); socket.on('connect', function() { socket.send('User has connected!'); }); socket.on('message', function(data) { var new_message = document.createElement('div'); new_message.innerHTML = data; document.querySelector('#messages').appendChild(new_message); }); function sendMessage() { var message = document.querySelector('#message_input').value; socket.send(message); } </script> </head> <body> <h1>Flask Websocket Chat</h1> <div id="messages"></div> <input type="text" id="message_input"> <button onclick="sendMessage()">Send</button> </body> </html>
By running the above code, you can implement a simple WebSocket chat room.
Conclusion:
This article introduces how to integrate WebSocket under the Flask framework and provides a simple chat room example. Through the Flask-SocketIO plug-in, WebSocket can be easily used to implement real-time communication functions. When developing Web applications, combining WebSocket can improve user experience and achieve real-time data updates, instant messaging and other functions. I hope this article will help you use WebSocket under the Flask framework.
The above is the detailed content of WebSocket application practice guide under the Flask framework. For more information, please follow other related articles on the PHP Chinese website!