0

On the client side I have the main code and a class. If I call the foo function in the class, it sends some data to the server, it processes it and sends it back to the class. My question is that how can I return that data to the main code?

Here is my class:

    def foo(self, a, b, c):
        dataj = {"t": "t",
                 "data": {
                     "a": a,
                     "b": b,
                     "c": c
                 }}
        self.__client_socket.send(json.dumps(dataj).encode())

    def __receive_data(self):
        while True:
            data = self.__client_socket.recv(1024)
            data = json.loads(data.decode("utf-8"))
            if data["a"] == "b":
                #return data to main code

Main code:

data = a.foo(1, 2, 3)
Nyikus
  • 23
  • 1
  • 6

1 Answers1

1

I am assuming when you want this data returned, the rest of your main code cannot be done without this data, so you could make a callback function that you give to the client object. And also next time please provide a minimal-reproducible example as it would be easier for anyone helping with your code to test it themselves.

So a solution could look like:

# client class
def foo(self, a, b, c):
    dataj = {"t": "t",
             "data": {
                 "a": a,
                 "b": b,
                 "c": c
             }}
    self.__client_socket.send(json.dumps(dataj).encode())


def set_on_recv(self, callback):
    self.on_recv_cb = callback


def __receive_data(self):
    while True:
        data = self.__client_socket.recv(1024)
        data = json.loads(data.decode("utf-8"))

        # Check if self.on_recv_cb is callable, meaning we can call it like a function
        if callable(self.on_recv_cb):
            # call the function we provided and pass in the json data
            self.on_recv_cb(data)


# inside of client class
def set_on_recv(self, callback):
    self.on_recv_cb = callback


# end of client class


# outside of client class
def handle_data(data):
    # this code will be called when data is received by the client socket
    if data["a"] == "b":
        pass


my_client = client()  # no provided class
my_client.set_on_recv(handle_data)
# sends the data to the server
my_client.foo(1, 2, 3)
# then once the client receives the data, __receive_data calls the handle_data function
# that we passed into set_on_recv


# Assuming you have __receive_data in another thread,
# I put input to not exit the application before receiving data
input()
Jesse_mw
  • 105
  • 2
  • 11