Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How use socketio decorator within another class #390

Closed
sraboncmc opened this issue Nov 29, 2019 · 9 comments
Closed

How use socketio decorator within another class #390

sraboncmc opened this issue Nov 29, 2019 · 9 comments
Labels

Comments

@sraboncmc
Copy link

sraboncmc commented Nov 29, 2019

Hi Miguel
I tried to use socketio.Client within a class where i can call socketio and its related event frequently.But dnt understand how figure out it.
It works fine on normal python file.

i m a part time coder,so plz dnt laugh on my coding.
Thanks in advance.

import socketio

class warSock:

    global mwar
    global name
    global ps
    mwar = socketio.Client()

    def __init__(self, name, ps):
        self.name = name
        self.ps = ps

    @mwar.event
    def connect(self):
        print('connected to server')

    @mwar.on('login')
    def on_login(data):
        print data

    def connectme(self):
        mwar.connect('http://localhost')

    def dc(self):
        mwar.disconnect()
@miguelgrinberg
Copy link
Owner

What part of this does not work? The only thing I noticed is that the on_login method is missing self.

As a side note, you may want to look at class-based namespaces in the documentation, as they already provide a way to implement events as methods in a class.

@sraboncmc
Copy link
Author

Thanks for your reply.
Problem was from here

@mwar.event
def connect(self):
print('connected to server')

sio wants connect(), but here class wants connect(self)
thats why sio call argument typeError (something like this)

@sraboncmc
Copy link
Author

And i think i sort out this by putting all sio related events inner function(def) of class def. And it works still.
And So much thanks for your great creation.I tried it 9 month earlier,bt i failed to connect single one.
may be i failed to understand the concept of decorator.

I have a request for connection establishment. It got hang on ide as like httplib connection.
I used socketio js and java client.Those are faster.

@Zartris
Copy link

Zartris commented Jun 24, 2020

This might be old and you have solved it.
If you don't need the self functionality in connect just make it static like this:

@staticmethod
@mwar.event
def connect():
print('connection established')

@Robokishan
Copy link

Robokishan commented Mar 1, 2021

i know this is old but i wanted to have this kind of functionality and i have done this

import socketio
import json

class Wrapper_class():
        sio = socketio.Client()

        def __init__(self):
            pass
        def setup(self):
            self.call_backs()
            self.sio.connect('http://localhost.local:8081')

        def loop(self): 
            self.sio.wait()

        def call_backs(self):
            @self.sio.event
            def connect():
                self.sio.emit('subscribe','room')
                print('connection established')
                
            @self.sio.on("docs")
            def raw_data(data):
                print(f"Data Received {data}")


            @self.sio.event
            def auth(data):
                print(f"Data Received {data}")


            @self.sio.event
            def disconnect():
                print('disconnected from server')
        def run(self):
            self.setup()
            self.loop()

wrapper = Wrapper_class()
wrapper.run()

@paulbuer
Copy link

paulbuer commented Aug 19, 2021

@Robokishan
@miguelgrinberg

wrapper = Wrapper_class()
wrapper.run()

Sorry for this noob questions, I'm a python beginner. Please help me.
I'm using flask-socketio with python-socketio client. And I copied the solution above because I also want to control what to emit from those events declared in the client wrapper class.

  1. How to send events declared inside call_backs function to the socketio server using the wrapper instance? How to invoke?
  2. Will self.loop() blocks until disconnect event happens? If there is code after wrapper.run(), will it also be blocked until the socket connection ended?
  3. What if I want to have multiple namespaces, can I connect them all first like this (see below)? And afterwards, I can emit to any namespace since they're all connected with the same sid?
  4. Then if there is code after wrapper.run(), let's say I want to emit to a specific namespace, can I use:
    wrapper.<function_to_call_with_the_emit_command_to_server>? And then return a response message status?
  5. How to detect if self.loop() was ended (socket disconnected) in the wrapper instance? What to do with the wrapper.run() ?
class Wrapper_class():
    sio = socketio.Client(logger=True, engineio_logger=True)
    latest_status = None
    namespaces = ['/', '/info']

    def __init__(self, url, headers=None, auth=None):
        self.url = url
        self.headers = dict() if not headers else headers
        self.auth = auth

    def setup(self):
        self.call_backs()
        self.sio.connect(self.url, headers=self.headers, auth=self.auth, namespaces=self.namespaces)

    def loop(self):
        self.sio.wait()

     def call_backs(self):
         ....

@miguelgrinberg
Copy link
Owner

@paulbuer My suggestion is that you first make your client work in the standard way. Once you have it working, many of your questions will be more clear to you. Also, let me mention one more time that this package has class-based namespaces for implementing the client in a class. Maybe that is enough for your needs and you don't need to invent a new wheel for this.

@paulbuer
Copy link

@miguelgrinberg
Thank you so much for your response. I will do what you said and more power to you sir.
I also saw flask-sock, your recent project. I would definitely try in the next release.

@mbwmbw1337
Copy link

i know this is old but i wanted to have this kind of functionality and i have done this

import socketio
import json

class Wrapper_class():
        sio = socketio.Client()

        def __init__(self):
            pass
        def setup(self):
            self.call_backs()
            self.sio.connect('http://localhost.local:8081')

        def loop(self): 
            self.sio.wait()

        def call_backs(self):
            @self.sio.event
            def connect():
                self.sio.emit('subscribe','room')
                print('connection established')
                
            @self.sio.on("docs")
            def raw_data(data):
                print(f"Data Received {data}")


            @self.sio.event
            def auth(data):
                print(f"Data Received {data}")


            @self.sio.event
            def disconnect():
                print('disconnected from server')
        def run(self):
            self.setup()
            self.loop()

wrapper = Wrapper_class()
wrapper.run()

Thank you for this. @miguelgrinberg perhaps add this to the docs? I am now using this setup which works great. Otherwise perhaps we update the decorators to work within a class environment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

6 participants