Sujet : Re: Best (simplest) way to share data
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 08. Jul 2024, 17:36:57
Autres entêtes
Organisation : Stefan Ram
Message-ID : <server-20240708162329@ram.dialup.fu-berlin.de>
References : 1 2 3
Chris Green <
cl@isbd.net> wrote or quoted:
That's exactly the sort of solution I was wondering about. Is there a
ready made module/library for handling this sort of thing? Basically
it will just be a string of a few tens of characters that would be
kept up to date by one process and asked for by all the others.
I'm not an expert here, and just quickly tried to make it
run, so the code will still contain errors and not contain
something necessary, but might give you a starting point.
A process doing something (here: printing an incrementing value
named "info") and also serving requests from other processes
for this "info" value:
import asyncio
import socket
class Server:
def __init__( self ):
self.info = 0
async def handle_client( self, reader, writer ):
data = await reader.read( 100 )
message = data.decode()
addr = writer.get_extra_info( 'peername' )
print( f"Received {message!r} from {addr}" )
if message.strip() == "getinfo":
writer.write( str( self.info ).encode() )
await writer.drain()
writer.close()
await writer.wait_closed()
async def print_number( self ):
while True:
print( self.info )
self.info += 1
await asyncio.sleep( 1 )
async def serve( self ):
server = await asyncio.start_server( self.handle_client, '127.0.0.1', 8888 )
addr = server.sockets[0].getsockname()
print( f'Serving on {addr}' )
async with server:
await asyncio.gather( server.serve_forever(), self.print_number() )
asyncio.run( Server().serve() )
, and an example client:
import socket
import time
while True:
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.connect( ( '127.0.0.1', 8888 ))
s.send( "getinfo".encode() )
data = s.recv( 100 )
message = data.decode().strip()
print( f"Received: {message}" )
time.sleep( 3 )
.