Code Monkey home page Code Monkey logo

Comments (7)

miguelgrinberg avatar miguelgrinberg commented on May 11, 2024 86

When you want to emit from a regular route you have to use socketio.emit(), only socket handlers have the socketio context necessary to call the plain emit().

from flask-socketio.

miguelgrinberg avatar miguelgrinberg commented on May 11, 2024 1

@NotLeet If you are working with Flask, then you should, in general, use emit(), which is context-aware, so it works well in a Flask event handler. If you want to emit from a background thread, you can copy the request context and still use emit().

The socketio.emit() method gives you direct access to the Socket.IO engine, without the Flask wrapper. You may want to use this function, I guess, but you don't really need to. You make it sound like these two emit options are at the same level but they are not. The emit() function is Flask specific, socketio.emit() is not, and in fact, emit() is implemented by calling the lower level socketio.emit().

So what do you think the documentation should say? I would rather you always use emit(), there is no use case where emit() wouldn't work, as long as you have a Flask request context.

from flask-socketio.

miguelgrinberg avatar miguelgrinberg commented on May 11, 2024 1

@linuxson27 the emit function tries to send the event back to the sender of an originating event. Since there is no originating event in this case, you have to indicate who the addressee is.

Are you storing the sid value for your clients? You need to add room=sid to the call, with the sid for the client you want to address. You can also pass the name of a room you created, or if you prefer, pass broadcast=True to send the event to all clients.

from flask-socketio.

seandmatthews avatar seandmatthews commented on May 11, 2024

Hey Miguel, I love your work, but as a first time user of this library this issue did catch me.
It's mentioned briefly in your documentation, here,

"Note that socketio.send() and socketio.emit() are not the same functions as the context-aware send() and emit()."

and obviously I found this answer in Google, but it may be worth it to make a small note in the flask-socketio documentation highlighting this potential stumbling block.

Anyway, I'm looking forward to your new flask mega-tutorial, and thanks again for all you do.

from flask-socketio.

linuxson27 avatar linuxson27 commented on May 11, 2024

Hi, been struggling with whether to use socketio.emit() and emit() myself...have a Flask application where I am just trying to emit a signal server side to the client to confirm that a MongoDB insert() method has indeed fired and completed. After hours of pulling my hair out, I finally came across this thread, and noticed the use of just emit(), which I have implemented (see below):

@app.route('/', methods=['GET', 'POST'])
def home():
    register_form = RegisterForm()

    if register_form.validate_on_submit():
        users = mongo.db.users

        users.insert({
            'user': register_form.name.data,
            'password': register_form.password.data,
            'role': register_form.role.data})

        def ack():
            print('Message was received')

        emit('name_added', 'User has been added', namespace='/', callback=ack)

    return render_template('index.html', register_form=register_form)

Still finding my feet with Flask, so pardon any bad coding on my behalf. This emit signal is however returning an error: AttributeError: 'Request' object has no attribute 'sid'
How do I fix this?

PS: This is my code client side...

<body>
    <div class="container">
        <div class="d-flex justify-content-center mt-5">
            <div class="w-25 text-center mt-5">
                <form method="POST" action="{{url_for('home')}}">
                    {{register_form.csrf_token}}
                    {{register_form.name(class_='form-control font-weight-light mb-4', type='text', placeholder='username')}}
                    {{register_form.password(class_='form-control font-weight-light mb-4', type='password', placeholder='password')}}
                    {{register_form.role(class_='custom-select mt-2 mb-4')}}
                    <button type="submit" id="sendButton" class="btn btn-raised btn-info mt-4 w-100 rounded-0">Send</button>
                </form>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            var socket = io.connect('http://127.0.0.1:5000');

            socket.on('name_added', function(data) {
                console.log(data)
            })
        });
    </script>
</body>

from flask-socketio.

tahir80 avatar tahir80 commented on May 11, 2024

Hi Miguel,

I am trying to call socketio.emit function but it did not work.

here is the code:

from app import socketio
from flask_socketio import SocketIO, emit, join_room, leave_room, \
    close_room, rooms, disconnect


def msg_process(msg, tstamp):
     socketio.emit('start_your_task', {'message': [worker.AMT_worker_id]})


@main.route('/api/from', methods = ['GET', 'POST', 'PUT'])
     msg_process(js['Message'], js['Timestamp'])

what I am doing wrong? I did not share the complete code

from flask-socketio.

miguelgrinberg avatar miguelgrinberg commented on May 11, 2024

@tahir80 what do you mean by "it didn't work"? There isn't anything obviously wrong in the code that you are showing me, the problem must be somewhere else.

from flask-socketio.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.