I am just beginning to learn Flask SocketIO. The basic requirement is to gather all the client (along with info) that are connected to server. Below code is written to do just that. Username is collected on click of a button.
#main.py
from flask import Flask, render_template, request, session, jsonify
from flask_socketio import SocketIO, emit, send
app = Flask(__name__)
socketio = SocketIO(app, manage_session=False)
clients = []
@socketio.on('client_connected', namespace='/connect')
def handle_client_connected_event(username, methods=['GET', 'POST']):
clients.append(
{
'client_session': request.sid,
'client_username': username,
'client_ip': request.access_route
}
)
print(clients)
@app.route('/')
def index(methods=['GET', 'POST']):
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0')
And Client side code:
//JS
var socket = io.connect('http://' + document.domain + ':' + location.port);
var socket_messages = io.connect('http://' + document.domain + ':' + location.port+'/connect');
$('#send_username').on('click', function(){
socket_messages.emit('client_connected', $('#username').val());
});
and lastly HTML
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
<title>Document</title>
</head>
<body>
<input type="text", id="username">
<button id="send_username">Submit Username</button><br>
<!-- Connected User: -->
</body>
</html>
I am unable to get client info using this piece of code. Any insights as to where I may be going wrong? Thanks for your help