def P2P_registration(): '''Function which sends the initial Register message''' global RS_server, RS_port, RFC_client, RFC_Server_port, cookie client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((RS_server, RS_port)) RFC_client = client_socket.getsockname()[0] in_msg_reg = message() in_msg_reg.statuscode = 'ERR' out_msg_reg = message() out_msg_reg.mtype = 'Register' out_msg_reg.statuscode = 'OK' out_msg_reg.hostname = RFC_client out_msg_reg.headertag ='WelcomePort' # should assign this dynamically based on rfc server port value out_msg_reg.headervalue = str(RFC_Server_port) out_msg_reg.data = '' out_msg_reg.create_raw() print "\nRegistration message sent:", out_msg_reg.raw,"|||\n" client_socket.send(out_msg_reg.raw.encode()) # Send the Register message RS_reply = client_socket.recv(1024).decode() # Get the reply from the RS for the register message in_msg_reg.create_fields(RS_reply) cookie = in_msg_reg.headervalue print "\nRegistration reply received:", in_msg_reg.raw,"|||\n" client_socket.close() time.sleep(20) return None
def handler(self): time = (datetime.datetime.now() + datetime.timedelta( minutes=self.user.bucket['send_message_delay'])) outbox[time] = message(self.message.text, users[self.user.login], self.user.bucket['send_message_to'], self.message.attachments) self.user.notify(message('Sent!')) self.user.next_action(start)
def downloadBoot(self): elapsed = time.time() - self.startTransferTime message(' flash erased in %.1f seconds'%elapsed,'note') note('Download image ') self.pointer = self.start self.writeCommand() self.chunk = 256
def writeData(self): if not self.verbose: message('.', "note") self.chunk = min(self.chunk, self.end - self.pointer) if self.chunk % 4: error('Transfer size not a multiple of 4: %d'%self.chunk) note('Image size: %d'%self.size) index = self.pointer - self.start self.pointer += self.chunk data = self.image[index:index+self.chunk] self.onAck(self.checksummed([self.chunk-1] + data), self.writeCommand)
def block_broadcast(): log.info('Broadcasting block status...') m = message("",config.message_port) while True: m.reply(int(config.global_height) -1) time.sleep(config.broadcast_time_span) m.send_all()
def hide_id(self): self.user.show_service_name = False self.user.notify( message(""" Your service id was hidden. Your messages' receivers would not see \ your service id. You couldn't be found by your service id. """))
def try_sending_message(self, des_node, mes, ts, replicaID, LINK_EXISTS, specBW): if mes.last_sent <= ts: max_end = ts + maxTau if max_end > T: max_end = T for te in range(ts + 1, max_end): spec_to_use = [] for s in range(4): if LINK_EXISTS[self.ID, des_node.ID, s, int(ts - startTime), int(te - startTime)] == 1: spec_to_use.append(s) for spec in range(len(spec_to_use)): if can_transfer(mes.size, spec_to_use[spec], (te - ts), specBW, self.ID, des_node.ID, ts, mes): new_message = message(mes.ID, mes.src, mes.des, mes.genT, mes.size) new_message.set(te, replicaID, te, self.ID) des_node.buf.append(new_message) return True return False
def recv(self): """ Recieve a message (class message) from a connected peer. """ if self.CONNECTED == False: print "Not connected to any peer!" return self.sock.setblocking(1) # Recieve message # recv wont block for some reason.... spinlocking ftw! ^^ # Need to look in to this... buf = '' while buf == '': buf = self.sock.recv(1) ll = int(buf) buf = '' while buf == '': buf = self.sock.recv(ll) l = int(buf) buf = '' while buf == '': buf = self.sock.recv(l) message_list = buf.split() msg = message() for token in message_list: msg.add(token) return msg
def do_GET(self): global my_chatroom, my_user, my_bot, html_blueprint msg = urlparse(self.path).query if msg.startswith("message="): msg = msg[8:] msg = urllib.parse.unquote(msg.replace("+", " ")) if msg == ":clear": my_chatroom.history = [] else: if msg != "": out = my_chatroom.on_msg(message(msg.lower(), my_user)) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() m = "" for i in my_chatroom.history: if i.user.name == my_bot.name: m += "<div class=\"bot\">" + i.text + "</div>\n" else: m += "<div class=\"user\">" + i.text + "</div>\n" self.wfile.write( html_blueprint.replace("<!-- messages -->", m).encode("utf-8")) return
def phase2(self): import string # verify the message at each backup (if valid then send a Prepare Request) print("\nPHASE2::<<PREPARE>>") messagePhase2 = 0 for i in range(len(self.VIEW.backups)): m = self.VIEW.backups[i][1] if self.valid(m): # print("valid") for j in range(len(self.VIEW.backups)): if self.VIEW.backups[j][0] != self.VIEW.backups[i][0]: mess = self.VIEW.backups[i][1].message # if faulty node then wrong message will be sent # then the decrypted message will not be same if j + 1 in self.falutyNodes: mess = ''.join(random.choices(string.ascii_uppercase +\ string.digits, k = 20)) prepMessage = message("Prepare", self.VIEW.viewNo, mess, self.digest) self.VIEW.backups[j].append(prepMessage) self.VIEW.backups[j][2].prepareCount += 1 messagePhase2 += 1 print("PHASE2::Complete")
def create_unsuccess_ack_msg(self, text, msg_id="id"): header = message_header(self.id(), self.signature(), msg_id, 0, message_type.ack_failure ) #TODO per id usa un contatore di messaggi? payload = message_payload(text) ack_msg = message(header, payload) return ack_msg
def try_sending_message(self, des_node, mes, ts, replicaID, LINK_EXISTS, specBW): if mes.last_sent <= ts: max_end = ts + maxTau if max_end > T: max_end = T for te in range(ts + 1, max_end): spec_to_use = [] for s in S: if LINK_EXISTS[self.ID, des_node.ID, s, int(ts - startTime), int(te - startTime)] == 1: spec_to_use.append(s) for spec in range(len(spec_to_use)): if can_transfer(mes.size, spec_to_use[spec], (te - ts), specBW, self.ID, des_node.ID, ts, mes): # calculate energy consumed sensing_energy = math.ceil( mes.size / (specBW[self.ID, des_node.ID, spec_to_use[spec], ts])) * t_sd * sensing_power switching_energy = math.ceil( mes.size / (specBW[self.ID, des_node.ID, spec_to_use[spec], ts])) * idle_channel_prob * switching_delay transmission_energy = math.ceil( mes.size / specBW[self.ID, des_node.ID, spec_to_use[spec], ts] ) * idle_channel_prob * t_td * spectPower[ spec_to_use[spec]] consumedEnergy = sensing_energy + switching_energy + transmission_energy consumedEnergy = round(consumedEnergy, 2) self.energy += consumedEnergy des_node.energy += consumedEnergy new_message = message( mes.ID, mes.src, mes.des, mes.genT, mes.size, [ mes.band_usage[0], mes.band_usage[1], mes.band_usage[2], mes.band_usage[3] ]) new_message.set(te, replicaID, te, self.ID) new_message.band_used(spec_to_use[spec]) if new_message.ID == debug_message: print("time: ", ts, "src", self.ID, "des", des_node.ID, "prev Bands used", mes.band_usage, "next band ", new_message.band_usage) des_node.buf.append(new_message) return True return False
def send_message2(self, des_node, mes, ts, replicaID, LINK_EXISTS, specBW): if mes.last_sent < ts: S = [0, 2, 1, 3] for s in S: i = self.ID j = des_node.ID delay = find_delay(mes.size, s, specBW, i, j, ts) te = ts + delay if te < T: if LINK_EXISTS[i, j, s, ts, te] == 1: new_message = message(mes.ID, mes.src, mes.des, mes.genT, mes.size, mes.band_usage) new_message.set(te, replicaID, te, i) des_node.buf.append(new_message) return True return False
def create_txset_messages(self, transactions): msgs = [] num = len(transactions) while num > 50: tmp = transactions[0:50] header = message_header(self.id(), self.signature(), 'id', 1, message_type.transaction_set) payload = message_payload(transaction_set(tmp)) msgs.append(message(header, payload)) transactions = transactions[50:] num = len(transactions) header = message_header(self.id(), self.signature(), 'id', 0, message_type.transaction_set) payload = message_payload(transaction_set(transactions)) msgs.append(message(header, payload)) return msgs
def setServer(self, key, val, server_index): returnarray = [] msg = message("SET", (key, val), None, None, None) #nonsense values because message was implemented #after eventual consistency self.sendRequest(msg, server_index, returnarray) return returnarray[0]
def send(self, op): """ Sends the given operation to the server. """ tokens = op.split() msg = message() for token in tokens: msg.add(token) self.pb.send(msg)
def create_ledger_messages(self, transactions, seq): msgs = [] num = len(transactions) while num > 40: tmp = transactions[0:40] header = message_header(self.id(), self.signature(), 'id', 1, message_type.ledger) txset = transaction_set(tmp) payload = message_payload(full_ledger(seq, txset)) msgs.append(message(header, payload)) transactions = transactions[40:] num = len(transactions) header = message_header(self.id(), self.signature(), 'id', 0, message_type.ledger) txset = transaction_set(transactions) payload = message_payload(full_ledger(seq, txset)) msgs.append(message(header, payload)) return msgs
def _send_msg(self, message, *args): oid = self.oid = self.oid + 1 data = message_factory.pack(message(oid, *args)) cnt = self.socket.sendto(data, self.address) self.response = None name = message.__class__.__name__ _logger.info('Sent %s message to %s', name, self.address) _logger.debug('Sent %d bytes: %r', cnt, data) return oid
def _send_message(self, message, *args, **kwargs): name = message.__name__ params = self.message_factory.get_params(message)[1] try: message_ = message(*args, **kwargs) except TypeError, e: e, f = re.findall(r'[^_a-z](\d+)', e.message, re.I) raise TypeError('%s takes exactly %d arguments (%d given)' % (message.__doc__, int(e) - 1, int(f) - 1))
def add_messages(self, time, lines): for line in lines: line_arr = line.strip().split() if int(line_arr[5]) == time: new_mes = message(line_arr[0], line_arr[1], line_arr[2], line_arr[5], line_arr[4]) src = int(line_arr[1]) self.nodes[src].buf.append(new_mes)
def about(self): msg = """ VTBot - send and receive messages from anywhere. \ We erase the boundaries between social networks.\n\n\ Telegram: t.me/vtbot_bot\n\ VK: vk.com/vtbot\n\ GitHub: github.com/farhit1/vtbot """ self.user.notify(message(msg))
def send(self, conn): #creating a sync object syncObj = syncObject(self.tt, self.log_list) s = socket.socket() m = message("sync_response", syncObj) s.connect(conn) s.send(pickle.dumps(m,0)) s.close()
def handle(self): try: msg = self.message.text for command in self.commands: if command.is_shown(self.user) and msg == command.alias: exec('self.%s()' % command.execute.__name__) return self.handler() except incorrect as e: self.user.notify(message('Error: %s' % e.comment))
def PhaseI(self, leadermsg): print("LEADER: ", self.VIEW.leader) print("phaseI started .................................") for i in range(self.GRAPH.N + 1): if i == self.VIEW.leader or i in self.FaultyLeader: continue else: msg = message("Preprepare", self.VIEW.viewNo, leadermsg, self.encrypt(leadermsg), self.key) self.VIEW.backups.append([i, msg])
def info(self): self.user.notify( message( "%s\n\nAvailable commands:\n%s\n\n" % (self.desc, '\n'.join( map( lambda command: "%s - %s" % (command.alias, command.comment), (command for command in self.commands if (command.comment and command.is_shown(self.user))))))) )
def create_success_ack_msg(self, content, type=message_type.ack_success, msg_id="id", seq_num=0): header = message_header( self.id(), self.signature(), msg_id, seq_num, type) #TODO per id usa un contatore di messaggi? payload = message_payload(content) ack_msg = message(header, payload) return ack_msg
def totalOrderMulticast(self, msg): print("Total order multicast entered") key = msg.getPayload()[0] val = msg.getPayload()[1] broadcast = message("BROADCAST", (key, val), self.server_id, -1, self.getClock()) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.connect(('127.0.0.1', self.middleware_port)) s.send(pickle.dumps(broadcast)) except ConnectionRefusedError: print("CONNECTION REFUSED DURING MULTICAST")
def getInfo(host, port): s = socket.socket() conn = (host,port) msg = message("info", None) send = pickle.dumps(msg,0) s.connect(conn) s.send(send) rcv = s.recv(4096) return int(rcv)
def look(self): """ Recieve a request to look around. Sends adjacent tiles to client.""" self.timeleft -= 1 if self._fire > 0: self._fire -=1 msg = message() tiles = self.get_adjecent_tiles() for each in tiles: msg.add(each[0]+"|"+each[1]+"|"+each[2]+"|"+each[3]) self.send(msg)
def handleClientEventual(self, conn, addr): msg = pickle.loads(conn.recv(1024)) #print(f"Server #{self.server_index} heard {data}") cmd = msg.getCmd() if (cmd == "GET"): key = msg.getPayload() msg = message(self.get(key), self.get(key), None, None, None) conn.send(pickle.dumps(msg)) elif (cmd == "SET"): key = msg.getPayload()[0] val = msg.getPayload()[1] self.set(key, val) ack = message("OK", "OK", None, None, None) conn.send(pickle.dumps(ack)) broadcastmsg = message("BROADCAST", (key, val), None, None, None) self.eventualBroadcast(broadcastmsg) elif (cmd == "BROADCAST"): key = msg.getPayload()[0] val = msg.getPayload()[1] self.set(key, val) ack = message("OK", None, None, None, None) conn.send(pickle.dumps(ack))
def lookup( host, port): s = socket.socket() conn = (host,port) msg = message("lookup", None) send = pickle.dumps(msg,0) s.connect(conn) s.send(send) rcv = s.recv(4096) posts = pickle.loads(rcv) display(posts)
def create_proposal_messages(self, transactions, r): msgs = [] num = len(transactions) while num > 45: tmp = transactions[0:45] header = message_header(self.id(), self.signature(), 'id', 1, message_type.proposal) txset = transaction_set(tmp) payload = message_payload( proposal(self.id(), r[0], txset, self.__blockchain.current_ledger_id())) msgs.append(message(header, payload)) transactions = transactions[45:] num = len(transactions) header = message_header(self.id(), self.signature(), 'id', 0, message_type.proposal) txset = transaction_set(transactions) payload = message_payload( proposal(self.id(), r[0], txset, self.__blockchain.current_ledger_id())) msgs.append(message(header, payload)) return msgs
def prova_size_txset(): c = client('127.0.0.12', 10000, []) r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') r6 = topology_node('r6', 'R') r7 = topology_node('r7', 'R') r8 = topology_node('r8', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) tx3 = transaction(r6, r5) tx4 = transaction(r2, r6) tx5 = transaction(r2, r7) tx6 = transaction(r2, r8) tx7 = transaction(r3, r6) tx8 = transaction(r3, r7) tx9 = transaction(r3, r8) tx10 = transaction(r7, r8) transactions = [tx] tx_set = transaction_set(transactions) header = message_header(c.id(), c.signature(), 'id', 0, message_type.transaction_set) payload = message_payload(tx_set) msg = message(header, payload) msg_bin = pickle.dumps(msg) print 'Size in bytes with one transaction: ' + str(sys.getsizeof(msg_bin)) tx_set.add_transaction(tx2) payload = message_payload(tx_set) msg = message(header, payload) msg_bin = pickle.dumps(msg) print 'Size in bytes with 2 transaction: ' + str(sys.getsizeof(msg_bin)) transactions = [tx3, tx4, tx5] for t in transactions: tx_set.add_transaction(t) payload = message_payload(tx_set) msg = message(header, payload) msg_bin = pickle.dumps(msg) print 'Size in bytes with 10 transaction: ' + str(sys.getsizeof(msg_bin))
def prova_invio_messaggi(): s = server('127.0.0.3', 10005, []) c = client('127.0.0.4', 10005, [s]) r2 = topology_node('r2', 'R') r3 = topology_node('r3', 'R') r5 = topology_node('r5', 'R') tx = transaction(r2, r5) tx2 = transaction(r3, r5) txset = transaction_set([tx, tx2]) mh = message_header(c.id(), c.signature(), 'm1', 0, message_type.transaction_set) mp = message_payload(txset) msg = message(mh, mp) c.send_all(msg)
def fire(self): """ Light a match, and be immune to grues for 9 minutes. Also killes any grue on you """ self.timeleft -= 1 msg = message() if self.numfire > 0: self._fire = 9 self.numfire -= 1 self.grue = False msg.add("ok") else: msg.add("out") self.send(msg)
def genMessageAndDigest(self, path, shortestDistance): # Concat the the path and Weight into a single Message self.message = "Path: " for i in range(len(path)): self.message += str(path[i]) + " " self.message += "\n" + "Traffic: " + str(shortestDistance) + "\n" # encrypt the Message and get the digest enc_type = Fernet(self.key) enc_message = enc_type.encrypt(self.message.encode('ASCII')) self.digest = enc_message return message("PRE-PREPARE", self.VIEW.viewNo, self.message, self.digest, self.key)
def disarm(self, direction): """ Disarm tile next to current position in given direction """ self.timeleft -= 2 if self._fire > 0: self._fire -=2 pos = [self.old[0], self.old[1]] if direction == "north": pos[1] -= 1 if direction == "south": pos[1] += 1 if direction == "west": pos[0] -= 1 if direction == "east": pos[0] += 1 if self.is_trap(pos[0], pos[1]): self.mapdata[pos[1]*self.mapw + pos[0]] = 1 msg = message() msg.add("ok") self.send(msg)
def game_intr(): game = message() intro = True while intro: gameDisplay.fill(white) game.message_to_screen("Welcome to Makeway",green,-60,"large") game.message_to_screen("Press c to continue.",black,-10) game.message_to_screen("Press q to Quit",green,10,) pygame.display.update() clock.tick(15) for event in pygame.event.get(): if event.type == pygame.QUIT: return 0 elif event.type== pygame.KEYDOWN : if event.key == pygame.K_q: return 0 elif event.key == pygame.K_c: intro=False gamem()
def send_movement(self): """ Updates the movement of the player and the grues. The result is sent to the client. """ self.update_grues() msg = message() tile = "tile" trap = "safe" grue = "safe" if self.grue: self.hitpoints -=1 if (self.new[0],self.new[1]) == (self.old[0],self.old[1]): # hit wall tile = "wall" elif ((self.new[0],self.new[1]) == (self.end[0],self.end[1])): # found toby tile = "toby" self.win = True if self.is_trap(self.new[0], self.new[1]): trap = "trap" self.hitpoints -= 1 if self.is_grue(self.new[0], self.new[1]): grue = "grue" self.grue = True for g in self.grues: if (g.x,g.y) == (self.new[0], self.new[1]): self.grues.remove(g) break if self._fire > 0: self.grue = False msg.add(tile) msg.add(trap) msg.add(grue) self.send(msg)
def inventory(self): """ Sends number of matches west to client. """ msg = message() msg.add(str(self.numfire)) self.send(msg)
elif text == 'auth_msg': auth_str = Message().auth_successful() try: chat_client.sock.sendall(auth_str) except Exception, e: sys.stdout.flush() try: chat_server.sock.sendall(auth_str) except Exception, e: sys.stdout.flush() elif text == 'send_file': file_to_send = raw_input("Type the name of the file to send: ") with open(file_to_send,'rb') as fts: content = fts.read() whole_message = message().payload(content) if len(whole_message) > 0 and whole_message != ['']: try: for i in range(len(whole_message)): if i == (len(whole_message)-1): chat_client.sock.sendall(Message().file_message(whole_message[i], True)) else: chat_client.sock.sendall(Message().file_message(whole_message[i], False)) except Exception, e: #print "Text input e client: " #print e sys.stdout.flush() try: for i in range(len(whole_message)): if i == (len(whole_message)-1):
def sink(self, s): message(s)
def sink2(self, s): ts = self.timestamp() message(ts+''.join(map(lambda x: ' '+hex(ord(x))[2:], s)), self.ui.Color2.currentText())
def main(self, filename, gamemode): """ Main program """ # Set up pygame pygame.init() self.screen = pygame.display.set_mode((640, 480), HWSURFACE) pygame.display.set_caption('Labyrinth') self.screen.fill((150,150,150)) myFont = pygame.font.SysFont("None", 90) # Load map self.load_map(filename, gamemode) self.setup_grues() self.draw_map() pygame.display.flip() # Player variables: self.timeleft = 13*60*2 self._fire = 0 self.numfire = 11 self.grue = False self.hitpoints = 5 self.win = False while 1: #print self.timeleft self.screen.fill((0,0,0)) for event in pygame.event.get(): if event.type == QUIT: exit()#return elif event.type == KEYDOWN: if event.key == K_ESCAPE: return msg = self.recv() op = msg.get(0) if self.hitpoints == 0: op = message() op.add("dead") self.send(op) break if self.timeleft <= 0: op = message() op.add("timeout") self.send(op) break if op == "north": self.north() elif op == "south": self.south() elif op == "east": self.east() elif op == "west": self.west() elif op == "look": self.look() elif op == "disarm": self.disarm(msg.get(1)) elif op == "fire": self.fire() elif op == "inventory": self.inventory() elif op == "quit": break if self._fire < 0: self._fire = 0 self.update_map() self.draw_map() #time.sleep(0.05) self.screen.blit(myFont.render(str(self.timeleft), 0, (255,255,255)), (500,10)) pygame.display.update() if self.win: print "Finished with score: " + str(self.timeleft) time.sleep(1) break self.cleanup()
def eraseBoot(self): message('connected') note('Erasing...') self.transferTimer.start(20000) self.onAck(self.checked(0x44), self.erasePages) self.setProgress.emit(.05)
def run(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #self.sock.bind(('', self.port)) self.sock.connect((self.HOST, int(self.PORT))) whole_inc_message = [] whole_file_inc_message =[] # Select loop for listen while self.running == True: inputready,outputready,exceptready = select.select ([self.sock],[self.sock],[]) for input_item in inputready: # Handle sockets data = self.sock.recv(4096) if data: in_data = message().break_message(data) #print "data message: " + str(in_data) if in_data["type"] == "\x04": if in_data["flag"] == "1": if routing.neigh_table[routing.find_uuid_in_neighbour_t(in_data["source"])][1] == str(self.sock) : #broken? self.sock.sendall(Message().ack()) else: print routing.neigh_table[routing.find_uuid_in_neighbour_t(in_data["source"])][1] #broken? elif in_data["type"] == "\x01": if in_data["flag"] == "4": #some cyckle to get all the in data #autorization #check if correct destination whole_inc_message.append(in_data["payload"]) self.sock.sendall(Message().ack()) elif in_data["flag"] == "8" and self.accept_file == "y": print "file transfer" f = open(self.file_name, 'a') try: f.write(in_data["payload"]) f.close() except Exception, e: f.close() self.sock.sendall(Message().ack()) sys.stdout.flush() elif in_data["flag"] =="1" and self.accept_file == "y": print "file transfer" f = open(self.file_name, 'a') try: f.write(in_data["payload"]) f.close() self.sock.sendall(Message().ack()) except Exception, e: f.close() self.accept_file = "no" sys.stdout.flush() elif in_data["flag"] =="1" and self.accept_file != "y": whole_inc_message.append(in_data["payload"]) print "("+in_data["source"]+"): "+ ''.join(whole_inc_message) #in_data["payload"] whole_inc_message = [] self.sock.sendall(Message().ack()) #file transfer init elif in_data["type"] == "\x02": if in_data["flag"] == "20": file_name_l = [] file_size_l = [] flie_name_s = False file_size_s = False for m in in_data["payload"]: if m != "0" and flie_name_s == False: file_name_l.append(m) elif m == "0" and flie_name_s == False: flie_name_s = True elif m != "0" and flie_name_s == True: file_size_l.append(m) file_size_s = True elif m == "0" and file_size_s == True: file_size_l.append(m) self.file_name = ''.join(file_name_l) file_size = ''.join(file_size_l) print "receiving file " + self.file_name + " size: " + file_size self.accept_file = raw_input('Accept file (y/n):') elif in_data["type"] == "\x02": if in_data["flag"] == "4": print "ack received: " + in_data["source"]
def main(args): message()
def run(self): HOST = '' conn_list = [] conn_out_list = [] s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST,self.PORT)) s.listen(5) conn_list.append(s) conn_list.append(sys.stdin) whole_inc_message = [] whole_file_inc_message =[] # Select loop for listen while self.running == True: #inputready,outputready,exceptready = select.select ([self.conn],[self.conn],[]) inputready,outputready,exceptready = select.select (conn_list,conn_out_list,[]) for sock in inputready: #New connection if sock == s: # Handle the case in which there is a new connection recieved through server_socket self.conn, self.addr = s.accept() conn_list.append(self.conn) print "Client (%s, %s) connected" % self.addr sys.stdout.flush() #for input_item in inputready: #else: # Handle sockets #try: try: data = self.conn.recv(4096) except Exception, e: data = None sys.stdout.flush() if data != None: in_data = message().break_message(data) #print "data message: " + in_data #print in_data if in_data["type"] == "\x04": if in_data["flag"] == "1": #print "in_data source: " + in_data["source"] #print "self address: " + str(self.addr[0])+":"+str(self.addr[1]) #print "con out list: " + str(conn_out_list) #print "con in list: " + str(conn_list) #print "soc in list: " + str(conn_list[2]) # can't use getname() routing.neighbour_t_add(in_data["source"], str(self.addr[0])+":"+str(self.addr[1]), 5) routing.display_n_table() #if routing.neigh_table[routing.find_uuid_in_neighbour_t(in_data["source"])][1] == self.conn : #broken? #self.conn.sendall(Message().ack()) #else: #print routing.neigh_table[routing.find_uuid_in_neighbour_t(in_data["source"])][1] #broken? elif in_data["type"] == "\x01": if in_data["flag"] == "4": #some cyckle to get all the in data #autorization #check if correct destination whole_inc_message.append(in_data["payload"]) self.conn.sendall(Message().ack()) elif in_data["flag"] =="1" and self.accept_file != "y": whole_inc_message.append(in_data["payload"]) print "(" + in_data["source"] + "): " + ''.join(whole_inc_message) #in_data["payload"] self.conn.sendall(Message().ack()) whole_inc_message=[] elif in_data["flag"] == "8" and self.accept_file == "y": print "file transfer" f = open(self.file_name, 'a') try: f.write(in_data["payload"]) f.close() self.conn.sendall(Message().ack()) except Exception, e: f.close() elif in_data["flag"] =="1" and self.accept_file == "y": print "file transfer" f = open(self.file_name, 'a') try: f.write(in_data["payload"]) f.close() self.conn.sendall(Message().ack()) except Exception, e: f.close() self.accept_file = "no" self.conn.sendall(Message().ack()) sys.stdout.flush() elif in_data["type"] == "\x02": if in_data["flag"] == "20": file_name_l = [] file_size_l = [] flie_name_s = False file_size_s = False for m in in_data["payload"]: if m != "0" and flie_name_s == False: file_name_l.append(m) elif m == "0" and flie_name_s == False: flie_name_s = True elif m != "0" and flie_name_s == True: file_size_l.append(m) file_size_s = True elif m == "0" and file_size_s == True: file_size_l.append(m) self.file_name = ''.join(file_name_l) file_size = ''.join(file_size_l) print "receiving file " + self.file_name + " size: " + file_size self.accept_file = raw_input('Accept file (y/n):') self.conn.sendall(Message().ack()) if in_data["flag"] == "4": print "ack received: " + in_data["source"]
def finish(self): self.transferTimer.stop() self.setAction.emit('Transfer') elapsed = time.time() - self.startTransferTime message(' finished in %.1f seconds'%elapsed,'note')