Skip to content

Publish-Subscribe

The publish-subscribe service enables an all-to-all multi directional exchange of data, by allowing nodes to subscribe and publish to topics. After subscription, they receive all messages that are published into the topic by any remote node.

Internally, the data distribution does not rely on naive flooding, however employs a gossip protocol.

The GossipSub Service

from hyveos_sdk import Connection
import asyncio
async with Connection() as connection:
gossip_sub = connection.get_gossip_sub_service()
# continue with usage of gossip_sub
# TODO

Example 1. Obtain the GossipSub service handler. Note the async environment.

Subscribing to a topic

Once a node is subscribed to a topic, it will receive any data published to that topic. subscribe(topic) will return an asynchronous stream of the eventually received messages.

subscriber_node.py
from hyveos_sdk import Connection
import asyncio
async def main():
async with Connection() as connection:
gossip_sub = connection.get_gossip_sub_service()
# Handle the incoming stream of messages
async with await gossip_sub.subscribe("topic") as messages:
async for message in messages:
text = message.msg.data.decode("utf-8")
if message.source:
direct_source = message.propagation_source # -> Peer
print(f"Received message from {message.source} via {direct_source}: {text}")
else:
print(f"Received message from unknown source: {text}")
asyncio.run(main())

Example 2. Subscribe to "topic" and continuously handle published messages. Note the async context manager in Python for proper disposal of the stream.

Publishing to a topic

Publishing to a topic will distribute the data to all nodes subscribed to the topic. Messages can be distinguished by their id.

publish(topic, data) returns a message id.

publishing_node.py
from hyveos_sdk import Connection
import asyncio
async with Connection() as connection:
gossip_sub = connection.get_gossip_sub_service()
id = await gossip_sub.publish("Hello, world!", "topic")
print(f"Published message with message_id: {id}")
asyncio.run(main())

Example 4. The node from Example 2 is now going to receive all messages that are published into 'topic'.


© 2025 P2P Industries. This documentation is licensed under the MIT License.
Cookie Policy    Privacy Policy