When I attempt to create my P2P network in Python, I have my first peer act like a server, then my next peer first connects to the first peer as a client, and then starts its own server for the following peer to connect to. I'm trying to use threading to get it so after I have a few peers connected as such:

P1                P2                   P3
[server]         [server]             [server]
      ^----------[client]             [client]

The third peer can send a message to the first peer (which is acting as server) and then the message is forwarded by the first peer to the second peer (acting as a client). I cannot figure out how to do this.

My main loop is essentially this, where the join_ip and join_port are for the current peer in the network the new one should join to, and the client_ip and client_port are the incoming peers ip and port that it should then listen on

def main():

    if self.first_peer is False:
        while True:
            t = threading.Thread(self.connect_to_peer(join_ip, join_port)).start()
            t2 = threading.Thread(self.become_server(self.client_ip, self.client_port)).start()

        while True:
             t = threading.Thread(self.become_server(self.client_ip, self.client_port)).start()

def become_server(self, ip, port):

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((ip, (int(port))))
    while True:   
        c, a = sock.accept()

def connect_to_peer(self, ip, port):
    peer_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    peer_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    wait_to_connect = True
    while wait_to_connect:
            t = threading.Thread(peer_sock.connect((ip, (int(port))))).start()
            wait_to_connect = False

    self.connections.append((peer_sock, port))

    self.connections_addresses.append((ip, str(int(port))))
    self.connections_count += 1

And then the new_connection function referenced above just takes the connection socket

0 Answers