3

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

S Verma
  • 103
  • 2
  • 9
  • The `methods=['GET', 'POST']` argument applies to Flask routes, it is not used in Flask-SocketIO event handlers. Probably not causing your problem, but you should remove it all the same as it serves no purpose. – Miguel Grinberg Nov 21 '19 at 10:39
  • @Miguel . This is something that I am also not able to figure out. How can I from the connection manager find out that if a particular client is currently connected to my server or not ? – Rohitashwa Nigam Nov 22 '20 at 09:22
  • @RohitashwaNigam I don't know what "connection manager" is. The client receives the `connect` event when the connection is established, and so that the server. That's how you know the connection is made. – Miguel Grinberg Nov 23 '20 at 18:33

0 Answers0