繁体   English   中英

PYTHON:从服务器接收到的数据返回

[英]PYTHON: Returning with received data from the server

在客户端,我有主代码和 class。 如果我在 class 中调用 foo function,它会向服务器发送一些数据,它会对其进行处理并将其发送回 class。 我的问题是,我怎样才能将该数据返回到主代码?

这是我的 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

主要代码:

data = a.foo(1, 2, 3)

我假设当您希望返回此数据时,如果没有此数据,您的主代码的 rest 将无法完成,因此您可以进行回调function 给客户端 ZA8CFDE6331BD59EB2AC96F8911C4B666 并且下次请提供一个最小可重现的示例,因为任何帮助您的代码的人自己测试它会更容易。

所以解决方案可能如下所示:

# 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM