Skip to content

Instantly share code, notes, and snippets.

@Hunter87ff
Created July 21, 2023 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hunter87ff/57ec9731dd86b7509544b996498b2c49 to your computer and use it in GitHub Desktop.
Save Hunter87ff/57ec9731dd86b7509544b996498b2c49 to your computer and use it in GitHub Desktop.
realtime flask server
<!-- templates/index.html -->
<html>
<body>
<h1>Real-Time Website</h1>
<div id="data-container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script>
<script>
const socket = io.connect('http://' + document.domain + ':' + location.port);
// Event listener to handle incoming data from the server
socket.on('updatedData', (data) => {
// Handle the updated data and update your website's frontend
document.getElementById('data-container').innerText = data;
});
// Function to send data to the server
function sendDataToServer() {
const dataToSend = 'Some updated data';
socket.emit('update', dataToSend);
}
</script>
</body>
</html>
# app.py
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret-key'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def handle_connect():
print('A user connected')
@socketio.on('disconnect')
def handle_disconnect():
print('A user disconnected')
@socketio.on('update')
def handle_update(data):
# Process the incoming data from the frontend as needed
# In this example, we'll simply broadcast the received data to all clients
emit('updatedData', data, broadcast=True)
if __name__ == '__main__':
socketio.run(app, host='localhost', port=8765)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment