Archer
Archer

Reputation: 1

How can make a persistent variable in asyncio instance?

I try to write a echo server based on python3-asyncio. I thought it can store and modify use variable in instance of asyncio class.

But I found that it seems all connection will make a new variable so it couldn't load previous value.

Follow is the code of asyncio server:

class EchoServer(asyncio.Protocol):
    count = 0
    ts_last_update = 0

    def connection_made(self, transport):
        self.transport = transport
        ts_now = int(time.time())
        print('Previous count is:', self.count)
        self.count += 1                     # add 1 each connection
        if (ts_now - self.ts_last_update) > (3600 * 24):
            print('When expired, do something here.')
            self.ts_last_update = ts_now    # record last update timestamp

    def data_received(self, data):
        recv = data.decode()
        self.transport.write(('We got msg:{}'.format(recv)).encode())

The result is following, count always is 0.

Server agent running on ('127.0.0.1', 18888)
Connection accepted
Previous count is: 0
do something here.
Receive: [aa]
Connection accepted
Previous count is: 0
do something here.
Receive: [bb]
Connection accepted
Previous count is: 0

Upvotes: 0

Views: 105

Answers (0)

Related Questions