Giter Club home page Giter Club logo

Comments (2)

magowiz avatar magowiz commented on June 8, 2024 1

@qstokkink thank you very much, your complete example clarified better what I miss and what I did wrong, in mine example I tried to provide not the whole code and of course reading a segmented code is harder, I understand, and also the fact wasn't working and I tried some changes, may have complicated this.

What I missed:

  • to register mine message handler : self.add_message_handler(TextMessage, self.on_text_message)
  • I changed the delay from 0 to 10 like you suggested me
  • rewrote the handler to have also another method name (I don't know if it is a good thing if collides with lamport clock ones) and fix it to use your logic

thank you very much for this fine example, I think my problem basically was I forgot to register a new message handler.

from py-ipv8.

qstokkink avatar qstokkink commented on June 8, 2024

Hi. Your code is a bit hard to read but I assume this is what you are trying to achieve:

import json
import os
from asyncio import run

from ipv8.community import Community, CommunitySettings
from ipv8.configuration import ConfigBuilder, WalkerDefinition, Strategy, default_bootstrap_defs
from ipv8.lazy_community import lazy_wrapper
from ipv8.messaging.payload_dataclass import dataclass
from ipv8.peer import Peer
from ipv8.util import run_forever
from ipv8_service import IPv8


@dataclass(msg_id=2)
class TextMessage:
    dictionary: str

    def fix_pack_dictionary(self, the_dictionary: dict) -> str:
        return json.dumps(the_dictionary)

    @classmethod
    def fix_unpack_dictionary(cls,
                              serialized_dictionary: str) -> dict:
        return json.loads(serialized_dictionary)


class MyCommunity(Community):
    community_id = os.urandom(20)


    def __init__(self, settings: CommunitySettings) -> None:
        super().__init__(settings)
        self.add_message_handler(TextMessage, self.on_message)

    def send_message_to_all(self) -> None:
        for peer in self.get_peers():
            self.ez_send(peer, TextMessage({'dictionary': 'hello'}))

    def started(self) -> None:
        self.register_task("start_communication", self.send_message_to_all, interval=10.0, delay=0)

    @lazy_wrapper(TextMessage)
    def on_message(self, peer: Peer, p_load: TextMessage) -> None:
        sentence = p_load.dictionary['dictionary']
        print(f"message from {peer}: {sentence}")


async def start_communities() -> None:
    for i in [1, 2, 3]:
        builder = ConfigBuilder().clear_keys().clear_overlays()
        builder.add_key("my peer", "medium", f"ec{i}.pem")
        builder.add_overlay("MyCommunity", "my peer",
                            [WalkerDefinition(Strategy.RandomWalk,
                                              10, {'timeout': 3.0})],
                            default_bootstrap_defs, {}, [('started',)])
        await IPv8(builder.finalize(),
                   extra_communities={'MyCommunity': MyCommunity}).start()
    await run_forever()

run(start_communities())

As a quick note: at delay=0 nobody will (probably) be connected yet, so you'll have to wait 10 seconds for the first messages to come in.

from py-ipv8.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.