I used flask-socketio to implement websocket. I used the eventlet/socketio sleep() function, which supposed to work asynchronously. And this is working in my custom event but when it is under the connect
event, it is not working. Here is the reproducible code:
Backend code:
from flask import Flask
from flask_socketio import SocketIO,emit,send
from eventlet import sleep
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/socket',methods=['POST', 'GET'])
def socket():
"""Landing page."""
return app.send_static_file('websocket_test.html')
@socketio.on('connect', namespace='/test')
def test_connect(auth):
for i in range(10):
emit('my_response',
{'data': str(i)})
##This does not work asynchronously
socketio.sleep(1)
@socketio.on('my_event', namespace='/test')
def test_message(message):
emit('my_response',
{'data': message['dataaa']})
for i in range(10):
# emit('my_response', {'data': str(i)})
emit('my_response',
{'data': message['dataaa']})
##But This work asynchronously
socketio.sleep(1)
if __name__ == '__main__':
socketio.run(app)
websocket_test.html:
<!DOCTYPE HTML>
<html>
<head>
<title>Socket-Test</title>
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
namespace = '/test';
var socket = io(namespace);
socket.on('connect', function(msg) {
console.log(socket.id);
console.log("connected");
console.log(msg);
$('#log').append('<br>' + $('<div/>').text(msg).html());
});
socket.on('my_response', function(msg, cb) {
$('#log').append('<br>' + $('<div/>').text('logs #' + msg.count + ': ' + msg.data).html());
});
socket.on('message', function(msg, cb) {
$('#log').append('<br>' + $('<div/>').text('logs #' + msg.count + ': ' + msg.data).html());
});
$('form#emit').submit(function(event) {
socket.emit('my_event', {dataaa: $('#emit_data').val()});
return false;
});
$('form#disconnect').submit(function(event) {
socket.emit('disconnect_request');
return false;
});
});
</script>
</head>
<body style="background-color:white;">
<h1 style="background-color:white;">Socket</h1>
<form id="emit" method="POST" action='#'>
<input type="text" name="emit_data" id="emit_data" placeholder="Message">
<input type="submit" value="Send Message">
</form>
<form id="disconnect" method="POST" action="#">
<input type="submit" value="Disconnect Server">
</form>
<h2 style="background-color:white;">Logs</h2>
<div id="log" ></div>
</body>
</html>