Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- import sys
- class Node:
- ip = ""
- port = "*"
- def __init__(self, address):
- self.ip = str(address[0])
- self.port = int(address[1])
- def __init__(self, ip, port):
- self.ip = str(ip)
- self.port = int(port)
- class P2P:
- node = None
- connectedNodes = []
- def __checkForConnection(self):
- try:
- data, nodeAddress = self.sock.recvfrom(1024)
- if not node in connectedNodes:
- print "Connection-request from " + nodeAddress[0] + ":" + nodeAddress[1] + ". Accept? (y/n)"
- choice = raw_input()
- if choice == "y":
- connectedNodes.append(Node(nodeAddress))
- self.sock.sendto("Connection-request accepted.", node.address)
- print "\t" + nodeAddress[0] + ":" + nodeAddress[1] + " has connected to us."
- else:
- self.sock.sendto("Connection-request denied.", nodeAddress)
- except:
- pass
- def __connect(self, node):
- print "\tTrying to connect to " + node.ip + ":" + str(node.port) + "..."
- self.sock.sendto(b"Hello.", (node.ip, node.port))
- waiting = True
- while waiting:
- data = self.sock.recvfrom(1024)
- if not data == None:
- print "\t'" + data + "'"
- if data == "Connection-request accepted.":
- connectedNodes.append(node)
- waiting = False
- return
- def __ask(self):
- print "(" + self.node.ip + "): "
- raw_data = raw_input()
- data = raw_data.split(' ')
- return data
- def __init__(self):
- ip = socket.gethostbyname(socket.gethostname())
- print "Hello " + ip + ". What port would you like to listen to today?"
- portEnteredCorrectly = False
- while not portEnteredCorrectly:
- port = int(input());
- if not port == None:
- self.node = Node(ip, port)
- portEnteredCorrectly = True
- else:
- print "Port entered incorrectly. Try again."
- self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- self.sock.bind((self.node.ip, self.node.port))
- self.sock.setblocking(0)
- print "Listening on port " + str(self.node.port) + "..."
- while True:
- self.__checkForConnection()
- inputtedValues = self.__ask()
- amValues = len(inputtedValues)
- if amValues == 1:
- if inputtedValues[0] == "exit":
- sys.exit(0)
- elif amValues == 3:
- if inputtedValues[0] == "connect":
- self.__connect(Node(inputtedValues[1], inputtedValues[2]))
- else:
- print "\tInput not recognised."
- else:
- print "\tInput not recognised."
- self.sock.close()
- if __name__ == "__main__":
- P2P()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement