Skip to content

Example implementation

Clooooode edited this page Jun 29, 2019 · 6 revisions

This page shows how to introduce this library into your own project.

1) Customize handler class

Write a Handler class which inherit AtomicP2P's Handler class.
If you have any problems while customizing one.
You can check out atomic_p2p.utils.communication.handler.py

from atomic_p2p.utils.communication import Handler, Packet


class CustomHandler(Handler):
    pkt_type = "custom_pkt"

    def __init__(self, peer):
        super(CustomHandler, self).__init__(
            peer=peer, pkt_type=type(self).pkt_type)
    
    def on_send_pkt(self, target):
        # Here is some operations you may want to take while sending a packet.
        # ... statements ...
        # This will show out at sender's logger.
        self.peer.logger.info("send")
        return Packet(dst=target, src=self.peer.server_info.host,
                      _hash=self.peer._hash, _type=type(self).pkt_type, _data={
                          "This is your test data": "12345"
                          })
    
    def on_recv_pkt(self, src, pkt, conn):
        # Here is some operations when you recv a packet from remote peer.
        # ... statements ...
        self.peer.logger.info("src: {}, pkt: {}".format(src, pkt))

2) Customize peer class

Write a Peer class which inherit AtomicP2P's Peer class .

from atomic_p2p.peer import Peer
from custom_handler import CustomHandler


class CustomPeer(Peer):

    def __init__(self, host, name, role, cert, _hash):
        super(CustomPeer, self).__init__(
            host=host, name=name, role=role, cert=cert, _hash=_hash)
    
    def _register_handler(self):
        # You have to use this super() statement to call parent's _register_handler method.
        # Otherwise, this peer is not capable to communicate with other peer.
        # Please check atomic_p2p.peer.__init__.py's Peer class for more details.
        super(CustomPeer, self)._register_handler()
        installing_handlers = [
            CustomHandler(self)
        ]
        for each in installing_handlers:
            self.pkt_handlers[type(each).pkt_type] = each

3) Start use it!

if __name__ == "__main__":
    import argparse
    from os import getcwd
    from time import sleep

    from atomic_p2p.peer.communication.net import JoinHandler
    from atomic_p2p.utils.security import (
        create_self_signed_cert as cssc
    )
    from custom_peer import CustomPeer


    parser = argparse.ArgumentParser()
    parser.add_argument('address', help='Service\'s host address.')
    parser.add_argument('-t', '--target', default='127.0.0.1:9000',
                        help='A peer address in Net.', dest='target')
    args, left = parser.parse_known_args()

    host = args.address
    target = args.target

    cert_file, key_file = cssc(cert_dir=getcwd(), cert_file="test.pem",
                               key_file="test.key")
    # This is a trick that allowed us to do any modified without restart a net.
    # For the reason of security, please DO NOT COPY AND PASTE AND USE while production.
    hash_str = "THIS IS A HASH"

    p = CustomPeer(
        host=host.split(":"), name="name_a", role="role_a",
        cert=(cert_file, key_file), _hash=hash_str)
    p.start()

    if target != host:
        # This is the manual way to join an exists net.
        # And the statement is equality to command 'peer join [target host]' 
        p.onProcess(['join', target])
        
        sleep(5)
        target_addr = target.split(":")
        target_addr[1] = int(target_addr[1])
        # This statement unicast the packet to target.
        p.handler_unicast_packet(host=(target_addr[0], target_addr[1]),
                                 pkt_type=CustomHandler.pkt_type)