def __init__(self, From, data, to):
self.From = From
self.data = data
self.to = to
class Address:
def __init__(self, ip, port):
self.ip = ip
self.port = port
def __init__(self, address):
address = address.split(":")
self.ip = address[0]
self.port = int(address[1])
def __str__(self):
return f"{self.ip}:{self.port}"
class Router:
async def handleConnection(self, reader, writer):
request = await reader.read(100)
message = json.loads(request.decode())
print(message)
if message["Type"] == 'join_request':
await self.process_join_request(Address(message["Address"]))
elif message["Type"] == 'join_notification':
await self.process_join_notification(Address(message["Address"]))
writer.close()
def __init__(self, address):
self.address = Address(address)
self.successor = None
self.predecessor = None
async def run(self):
address = self.address
self.server = await asyncio.start_server(self.handleConnection, address.ip, address.port)
print("Server Started")
async with self.server:
await self.server.serve_forever()
async def join(self, router):
await self.connectTo(router)
await self.send(Package(self, {"Type": "join_request", "Address": str(self.address)}, router))
async def notify(self, router):
await self.send(Package(self, {"Type": "join_notify", "Address": str(self,address)}, router))
async def process_join_request(self, address):
if self.successor is None:
self.successor = Router(address)
else:
await self.send(self, {"Type": "join_request", "Address": str(address)}, self.succussor)
async def process_join_notification(self, address):
new_node = Router(address)
new_node.successor = self
self.predecessor = new_node
async def connectTo(self, router):
strings = copy(self.__connections)
i = 0
for obj in strings:
strings[i] = str(obj.address)
i +=1
if str(router.address) not in strings:
print(f"Connect to {str(router.address)}")
self.__connections.append(router)
async def sendToAll(self, message):
for addr in self.__connections:
await self.send(Package(self, message, addr))
async def send(self, package):
try:
reader, writer = await asyncio.open_connection(package.to.address.ip, package.to.address.port)
except:
self.__connections.remove(package.to)
print("WARNING")
return
message = package.data
message["From"] = str(package.From.address)
message["To"] = str(package.to.address)
print("Send: ", message)
writer.write(json.dumps(message).encode("UTF-8"))
writer.close()
__connections = []
async def main():
router = Router(sys.argv[1])
server = router.run()
client = router.join(Router(sys.argv[2]))
await asyncio.gather(server, client)
asyncio.run(main())
Здравствуйте, подскажите, почему пишет, что сообщение отправилось, но оно не доходит до Handler?
Что за простыня
Обсуждают сегодня