Created
June 24, 2013 02:48
-
-
Save f-prime/5847469 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import json | |
import threading | |
import landerdb | |
class DemoP2P: | |
def __init__(self): | |
self.host = "" | |
self.port = 1337 | |
self.db = landerdb.Connect("nodes.db") | |
self.cmds = { | |
"hello":self.hello, | |
"get_nodes":self.get_nodes | |
} | |
self.supernode = ("", 1337) | |
def main(self): | |
self.send_get_nodes() | |
self.send_hello() | |
s = socket.socket() | |
s.bind((self.host, self.port)) | |
s.listen(5) | |
while True: | |
obj, conn = s.accept() | |
threading.Thread(target=self.handle, args=(obj, conn, ip)).start() | |
def handle(self, obj, ip): | |
""" | |
Data should look something like {"cmd":"hello", "port":int} | |
""" | |
data = obj.recv(1024) | |
if data: | |
data = json.loads(data) | |
if "cmd" in data: | |
if data['cmd'] in self.cmds: | |
self.cmds[data['cmd']](data, obj, ip) | |
def hello(data, obj, ip): | |
self.db.insert("nodes", {"ip":ip, "port":port}) | |
print ip, "says hello!" | |
def send_hello(self): | |
nodes = self.db.find("nodes", "all") | |
for x in nodes: | |
try: | |
s = socket.socket() | |
s.settimeout(1) | |
s.connect((x['ip'], x['port'])) | |
data = json.dumps({"cmd":"hello", "port":self.port}) | |
s.send(data) | |
except: | |
continue | |
def get_nodes(data, obj, ip): | |
with open("nodes.db", 'rb') as file: | |
for x in file.readlines(): | |
obj.send(x) | |
obj.close() | |
def send_get_nodes(self): | |
s = socket.socket() | |
s.connect(self.supernode) | |
data = {"cmd":"get_nodes"} | |
s.send(json.dumps(data)) | |
with open("nodes.db", 'wb') as file: | |
while True: | |
data = s.recv(1024) | |
if data: | |
file.write(data) | |
else: | |
break | |
if __name__ == "__main__": | |
DemoP2P().main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment