我当前的解决方案是在客户端更新数据时将更新的数据发送给客户端。实际上,这意味着客户机只有在自己发送消息时才能获得新消息。不是很有用。。。
我还想到了另一种方法,即让客户机每隔3秒左右向服务器请求信息,但这会使服务器上挤满大量的人。
我的大部分代码都是从
this part of the docs
所以你也可以对照一下。
(注意:要发送“消息”,您需要键入
asyncio.run(echo_client('username', 'message'))
. 这也是Python 3.7+)
import asyncio
async def echo_client(user, message):
reader, writer = await asyncio.open_connection(
'127.0.0.1', 41001)
user = str(user)
message = ''.join(message.split('\n'))
print(f'Sending from {user}: {message}')
writer.write((user + '\n').encode())
writer.write((message + '\n').encode())
await writer.drain()
data = await reader.readline()
data = data.decode().strip()
if data == 'Connection closed':
print('User disconnected')
else:
print('Users info')
for i in range(int(data)):
user = await reader.readline()
data = await reader.readline()
user = user.decode().strip()
data = data.decode().strip()
print(f'{user}: {data}')
# end for
print('Connection closed')
writer.close()
import asyncio
users = {}
async def handle_echo(reader, writer):
global users
user = await reader.readline()
data = await reader.readline()
addr = writer.get_extra_info('peername')
user = user.decode().strip()
data = data.decode().strip()
if data == '':
print(f'Recieved empty message from {addr!r}')
print(f'Closing connection to {addr!r}')
writer.write(b'Connection closed')
writer.close()
del users[user]
return
if data != 'update':
users[user] = data
print(f'Received {data} from {addr!r}')
print(f'Send: {[(i, j) for i, j in users.items()]}')
writer.write(f'{len(users)}\n'.encode())
await writer.drain()
for user, data in users.items():
writer.write(f'{user}\n{data}\n'.encode())
await writer.drain()
# end for
print('Closed the connection')
writer.close()
async def main():
server = await asyncio.start_server(
handle_echo, '127.0.0.1', 41001
)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
asyncio.run(main())
我的代码工作得很好,但我想找一个更好的替代方案。请解释您的实现是如何工作的,以及它将如何改进代码。
(我一会儿就要睡觉了,明天见。)