Sure! Here's an example of a simple peer-to-peer messaging class in Python using the asyncio library:
python
import asyncio
class PeerToPeer:
def __init__(self):
self.peers = []
self.server = None
async def start_server(self, port):
self.server = await asyncio.start_server(self.handle_client, port=port)
print(f"Server started on port {port}")
async with self.server:
await self.server.serve_forever()
async def handle_client(self, client, address):
print(f"Accepted connection from {address}")
self.peers.append(client)
async with client:
while True:
message = await client.read_message()
if message is None:
break
await self.broadcast(message)
print(f"Connection from {address} closed")
async def broadcast(self, message):
for peer in self.peers:
try:
await peer.write_message(message)
except asyncio.CancelledError:
pass
To use this class, you can create an instance of it and call the start_server method to start a server on a specific port. Other peers can then connect to the server and send messages to it, which will be broadcast to all connected peers: