我尝试编写一个基于 python3-asyncio 的回显服务器。我认为它可以在 asyncio 类的实例中存储和修改使用变量。
但我发现似乎所有连接都会创建一个新变量,因此它无法加载以前的值。
以下是异步服务器的代码:
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())
结果如下,计数始终为 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