efivg
CDCloudflare Developers
•Created by efivg on 3/13/2024 in #general-help
Flask Socketio wont work in tunnels
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import threading
app = Flask(__name__)
socketio = SocketIO(app)
def counter_thread():
count = 0
while count <= 100:
socketio.emit('counter_update', {'count': count}, namespace='/counter')
count += 1
socketio.sleep(1)
@app.route('/')
def index():
return "Hello, World!"
@app.route('/time1')
def time1():
return render_template('counter.html')
@socketio.on('connect', namespace='/counter')
def counter_connect():
global count_thread
if 'count_thread' not in globals():
count_thread = socketio.start_background_task(target=counter_thread)
if __name__ == '__main__':
socketio.run(app, port=8000)
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import threading
app = Flask(__name__)
socketio = SocketIO(app)
def counter_thread():
count = 0
while count <= 100:
socketio.emit('counter_update', {'count': count}, namespace='/counter')
count += 1
socketio.sleep(1)
@app.route('/')
def index():
return "Hello, World!"
@app.route('/time1')
def time1():
return render_template('counter.html')
@socketio.on('connect', namespace='/counter')
def counter_connect():
global count_thread
if 'count_thread' not in globals():
count_thread = socketio.start_background_task(target=counter_thread)
if __name__ == '__main__':
socketio.run(app, port=8000)
<!DOCTYPE html>
<html>
<head>
<title>Real-time Counter</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js"></script>
</head>
<body>
<h1>Real-time Counter</h1>
<div id="counter"></div>
<script>
var socket = io.connect('http://' + document.domain + ':' + location.port + '/counter');
socket.on('counter_update', function(data) {
document.getElementById('counter').innerHTML = 'Counter: ' + data.count;
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Real-time Counter</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.3.1/socket.io.js"></script>
</head>
<body>
<h1>Real-time Counter</h1>
<div id="counter"></div>
<script>
var socket = io.connect('http://' + document.domain + ':' + location.port + '/counter');
socket.on('counter_update', function(data) {
document.getElementById('counter').innerHTML = 'Counter: ' + data.count;
});
</script>
</body>
</html>
73 replies