Subscription

The files required for this example are:

  • app.py
  • hub.py
  • peer1.py
  • peer2.py

You will need to launch the hub.py before you launch the peers. After you launch the hub and however many peers you want, enter in your message and it will be echoed on all of the peers. A big thing to note is that the peers will not connect if the hub isn’t up. This is because subscriptions only happen when the peer is launched and there are no re-tries. So any peer launched before the hub will not get the event triggers.

Feel free to shut down the peers and try to enter your message again. You will see the hub will not error. It will simply ignore the missing peers. This will happen if the peers were to fail and error as well. The hub will ignore and just continue on with its own execution.

app.py

# configure this application as having its own network group through the
# environment set up
import os

# our peers will now all belong to the group, 'myApp'
os.environ['NET_GROUP'] = 'myApp'

# net imports
import net


@net.event("myEvent")  # <- this can be any value.
def something_happened(*args, **kwargs):
    return args, kwargs


# A subscription allows you to connect to an event on another peer. This does
# not need to always be a hub and peers can subscribe to events on any other
# peer the same way we did here minus the "hubs_only=True"
@net.subscribe("myEvent", hubs_only=True, on_host=True)
def handle_something_happened(message):
    """
    Simply print what happened.
    """
    print(message)

hub.py

# configure this as the hub of the group
import os

os.environ['NET_IS_HUB'] = 'True'

# Importing the application code will automatically launch the peer and begin
# listening for connection requests as well as set up the connection registry.
import app

if __name__ == '__main__':
    print("Enter the message to send to the peers subscribed to you.")
    while 1:
        # As you can imagine, this can be used anywhere in your application. In
        # this example, we are just going to take your message and broadcast it
        # to all the subscribed peers.
        your_message = input("Message: ")

        # This will trigger the "myEvent" that was wrapped on around this
        # function. When this is triggered, it will package up your message and
        # send it to the peers.
        app.something_happened(your_message)

peer1.py

# Importing the application code will automatically launch the peer and begin
# listening for connection requests as well as set up the connection registry.
import app

if __name__ == '__main__':
    # enter an endless loop so the peer will listen.
    while 1:
        pass