def sender(self, socket): logger.debug('Waiting for events') # subscribe self.eventbus.subscribe("core") self.eventbus.subscribe("plugin") # listen for events for event in self.eventbus.listen(): logger.debug("Event received: " + event.to_json()) if(event.name == "device.push"): packet = Packet() packet.dst = 25 packet.src = 1 packet.cmd = event.name packet.data = event.data #logger.debug("packet to send: " + packet.to_json()) addr = self.cache.get(packet.dst) if(addr == None): logger.error("Address not found for device: " + str(packet.dst)) continue address = addr.split(":") #address = ["192.168.1.1", 4444] # send packet socket.sendto(packet.to_json(), (address[0], int(address[1]))) logger.debug("Packet sent: " + packet.to_json() + " to: " + str(address)) continue
def ask_for_file(self, peer_info: Tuple[str, int], filename: str, chunks: List[int]) -> List[int]: """ Asks a peer for a given file. Args: peer_info: The address and port of a peer. filename: The filename to ask the peer for. chunks: The list of chunks to ask the peer for. Returns: The list of chunk Ids acquired for the file. """ # Create new TCP socket try: socket, port = utils.bind_UDP_port("") except PortBindingException: return False # Ask for chunks socket.sendto(utils.create_chunk_request_message(filename, chunks), peer_info) # Get each file, store in memory chunks_data = [] try: msg, addr = socket.recvfrom(constants.MAX_BUFFER_SIZE) filename, c_id, data = utils.parse_file_chunk_message(msg) self.shard_file_chunk(self.shard_dir, filename, c_id, data) chunks_data.append(c_id) except timeout: _logger.info(f"Timeout occured when waiting for file: {filename}.") return chunks_data
def recv(Socket, expected_ack): confirma = b'1' ans = b'' address = ('', -1) while (True): try: answer = Socket.recvfrom(limit) address = answer[1] body = answer[0] flag_fim = body[0:1] this_ack = body[1:33] real_msg = body[33:] this_ack = int(this_ack, 2) if (this_ack != expected_ack): Socket.sendto(confirma, address) continue else: Socket.sendto(confirma, address) expected_ack += 1 ans += real_msg if (flag_fim == b'1'): break else: continue except socket.timeout as e: continue return ans, address, expected_ack
def send(Socket, address, act_ack, msg): packs = [] while (len(msg) > 0): preff_size = min(limit - 33, len(msg)) cur_ack = act_ack + len(packs) cur_ack = transform_int(cur_ack) packs.append(cur_ack + msg[0:preff_size]) msg = msg[preff_size:] if (len(msg) == 0): packs[-1] = b'1' + packs[-1] else: packs[-1] = b'0' + packs[-1] for packet in packs: while (True): try: Socket.sendto(packet, address) serverAnswer, lixo = Socket.recvfrom(1) if (serverAnswer == b'1'): act_ack += 1 break except socket.timeout as e: continue return act_ack
def finish_request(self, request, client_address): data, socket = request with lock: if self.rate: time.sleep(len(data) / self.rate) self.buffer -= len(data) """ blockingly process each request you can add random loss/corrupt here for example: if random.random() < loss_rate: return for i in range(len(data)-1): if random.random() < corrupt_rate: data[i] = data[:i] + (data[i]+1).to_bytes(1,'big) + data[i+1:] """ """ this part is not blocking and is executed by multiple threads in parallel you can add random delay here, this would change the order of arrival at the receiver side. for example: time.sleep(random.random()) """ to = bytes_to_addr(data[:8]) print(client_address, to) # observe tht traffic socket.sendto(addr_to_bytes(client_address) + data[8:], to)
def announce_bc(socket, port, name, world): '''This function acts to broadcast the server's status of operation. Whether it's alive and ready to accept new players, or dead. ''' print 'Broadcasting thread started!' dest = ('<broadcast>', port) alive = True while alive: if world.keep_alive: message = "\HELLO;"+name socket.sendto(message, dest) if not world.keep_alive: message = "\DIE" for _ in range(3): socket.sendto(message, dest) sleep(0.2) alive = False #Try to sleep up to 5 seconds before broadcasting again. for _ in range(20): if world.keep_alive: sleep(0.25) else: break print "Broadcasting thread closed!" socket.close()
def Send(self,sequence,acknowledge,syn,ack,fin,data,s): self.flagNUM(syn,ack,fin) checksum=self.checksum(data) STPpacket = pickle.dumps(PackageSTP(sequence, acknowledge,checksum, syn, ack, fin, data)) socket.sendto(STPpacket, (self.receiver_host_ip, self.receiver_port)) s='snd'+s log.write('{:10s}{:10.2f} {:5s}{:12d}{:12d}{:12d}\n'.format(s,(time.time()-self.beginTime),self.Flag,sequence,len(data),acknowledge))
def send_chunk(chunk, cur_file_pos, socket, address): """Send a chunk to a printer. Args: chunk: The data to be sent. cur_file_pos (int): Reading position in the current file. socket (socket.socket): The socket to send to. address (tuple): A tuple of the printers ip and port. Returns: -- Raises: ValueError when chunk size is 0. """ chunk_array = bytearray(chunk) # Turn chunk into byte array chunk_size = len(chunk_array) # And get its size # geki hunch: this shouldnt get executed because chunk being 0-length # should have been caught in send_file()s 'if not chunk' if chunk_size <= 0: raise ValueError('Chunk size <= 0 (%s)' % chunk_size) # making data_array can fail with a ValueError # well catch it in send_file data_array = make_checksum_array(chunk, cur_file_pos) socket.sendto(data_array, address) log_response(socket)
def sendpacket(self, sequence, acknowledge, syn, ack, fin, data): self.flagNUM(syn, ack, fin) STPpacket = pickle.dumps( PackageSTP(sequence, acknowledge, syn, ack, fin, data)) socket.sendto(STPpacket, self.sender_addr) log.write('{:10s}{:10.2f} {:5s}{:12d}{:12d}{:12d}\n'.format( 'snd', (time.time() - self.beginTime), self.Flag, sequence, len(data), acknowledge))
def handle(data, remote): expression = pickle.loads(data) try: result = process(expression) print('Resolved', expression, 'to', result) socket.sendto(pickle.dumps(result), remote) except Exception as error: socket.sendto(pickle.dumps({'error': str(error)}), remote)
def sendto(self, data, flags_or_addr, addr=None): self._checkClosed() if self._sslobj: raise ValueError('sendto not allowed on instances of %s' % self.__class__) else: if addr is None: return socket.sendto(self, data, flags_or_addr) return socket.sendto(self, data, flags_or_addr, addr)
def finish_request(self, request, client_address): data, socket = request lock.acquire() if self.rate: time.sleep(len(data)/self.rate) self.buffer -= 1 lock.release() to = bytes_to_addr(data[:8]) # print(client_address, to) socket.sendto(addr_to_bytes(client_address) + data[8:], to)
def wrapped(): obj = {"body": {"answer": answer}, "method": "ADD", "route": "/answer"} socket.sendto(json.dumps(obj).encode(), ("localhost", 9000)) for k, v in buttons.items(): v.setEnabled(False) label.setText("Wating server response...") return
def send_discover(socket): cmd = array.array("B", [0] * DISCOVER_REQUEST_SIZE) cmd[0] = DISCOVER_PROTO_ID # Tag for identification of the protocol cmd[1] = DISCOVER_REQUEST # Request command cmd[2] = DISCOVER_ALL chksum = 0 for c in cmd[:3]: chksum -= c cmd[3] = chksum & 0xFF socket.sendto(cmd, ("<broadcast>", PORT))
def handle(data, remote): expression = str(data, encoding='UTF-8') try: result = process(expression) print('Resolved', expression.rstrip(), 'to', result) socket.sendto(bytes('= ' + str(result) + '\n', encoding='UTF-8'), remote) except Exception as error: result = str(error) socket.sendto(bytes('ERROR: ' + str(error) + '\n', encoding='UTF-8'), remote)
def prepare_write(socket, address): """Send a begin-communication GCode to a printer. Args: socket (socket.socket): The socket to send to. address (tuple) A tuple of the printers ip and port. Returns: -- """ logger.info("Sending M4001") socket.sendto(b"M4001", address) # SEND M4001 CODE TO PRINTER log_response(socket)
def send(Socket, adress, act_ack, msg): adress = (adress[0], 3000) msg = str(act_ack) + ' ' + msg print(str(adress)) while (True): try: Socket.sendto(msg.encode('ascii'), adress) serverAnswer, lixo = Socket.recvfrom(1024) if (serverAnswer.decode('ascii') == '-'): act_ack += 1 break except socket.timeout as e: continue return
def end_write(filename, socket, address): """Send a end-file-write GCode to a printer. Args: filename (str): The file name to write to. socket (socket.socket): The socket to send to. address (tuple): A tuple of the printers ip and port. Returns: -- """ logger.info("Sending M29") cmd = 'M29 ' + filename # SEND M29 CODE TO PRINTER socket.sendto(cmd.encode('utf-8', 'ignore'), address) log_response(socket)
def send_command(cmd, socket, address): """Send an arbitrary command to a printer. Args: cmd (str): The command to send. socket (socket.socket): The socket to send to. address (tuple): A tuple of the printers ip and port. Returns: -- """ # i replaced the manual sending of m4001 with a call to prepare_write prepare_write(socket, address) socket.sendto(cmd, address) # SEND CMD CODE TO PRINTER log_response(socket)
def sendto(self, data, addr, flags=0): self._checkClosed() if self._sslobj: raise ValueError("sendto not allowed on instances of %s" % self.__class__) else: return socket.sendto(self, data, addr, flags)
def finish_request(self, request, client_address): self.cnt = self.cnt + 1 data, socket = request lock.acquire() # print(f'network:sleep time {len(data) / self.rate}') if self.rate: time.sleep(len(data) / self.rate) self.buffer -= 1 lock.release() to = bytes_to_addr(data[:8]) # print(client_address, to) ss = segment.parse(data[8:]) # if self.cnt >= 3: # data = corrupt(data) # sss = segment.parse(data[8:]) # if(ss.checksum != sss.checksum): # print(f'{segment.getChecksum(sss)},{sss.checksum}') socket.sendto(addr_to_bytes(client_address) + data[8:], to)
def recv(Socket, expected_ack): confirma = '-' while (True): try: answer = Socket.recvfrom(1024) body = answer[0].decode('ascii') adress = answer[1] adress = (adress[0], 3000) this_ack, real_msg = body.split(' ', 1) this_ack = int(this_ack) if (this_ack != expected_ack): Socket.sendto(confirma.encode('ascii'), adress) continue else: Socket.sendto(confirma.encode('ascii'), adress) expected_ack += 1 return real_msg, adress except socket.timeout as e: continue return 'nunca deveria chegar aqui'
def handle_giving_port(self, socket: socket, shard_directory: str): """ A thread dedicated to listening for other peers communicating with it and sending them file chunks that this peer has locally. Args: socket: A configured socket ready to accept TCP connections. shard_directory: The temporary directory containing file shards. """ while constants.FOREVER: try: msg, peer_addr = socket.recvfrom(constants.MAX_BUFFER_SIZE) self.giving_data = True filename, chunks = utils.parse_chunk_request_message(msg) # No new messages. except timeout: continue # Main thread has ended. Terminate likewise except OSError: return except UnexpectedMessageReceivedException as e: _logger.error( f"Error while parsing message from peer. Error: {str(e)}") continue for chunk in chunks: with open(f"{shard_directory}/{filename}_{chunk}.chunk", "r") as f: data = f.read(constants.CHUNK_SIZE) socket.sendto( utils.create_file_chunk_message(filename, chunk, data), peer_addr) self.giving_data = True
def finish_request(self, request, client_address): loss_rate = 0.05 corrupt_rate = 1e-5 data, socket = request with lock: if self.rate: time.sleep(len(data) / self.rate) self.buffer -= len(data) if random.random() < loss_rate: return for i in range(8, len(data) - 1): if random.random() < corrupt_rate: data = data[:i] + (data[i] + 1).to_bytes( 1, 'big') + data[i + 1:] tem = np.random.normal(loc=0, scale=pow(2048 * 2 / 10240, 0.5), size=1)[0] time.sleep(abs(tem)) to = bytes_to_addr(data[:8]) print(client_address, to) # observe tht traffic socket.sendto(addr_to_bytes(client_address) + data[8:], to)
def open_connection(socket, client_conn, data, router): request = None try: payload = json.loads(data) request = Request(**payload) request.connection = client_conn try: response = router.resolve(request) if response != None: socket.sendto(response.encode(), client_conn) except Exception as e: print(e) socket.sendto( Response(code=codes.INTERNAL_ERROR, body="Internal error").encode(), client_conn) except Exception as e: print(e) socket.sendto( Response(code=codes.BAD_REQUEST, body="Invalid request").encode(), client_conn)
def handle(self): (data, socket) = self.request response = self.parse(data) if response: socket.sendto(response, self.client_address)
socket, info = ss.accept() while (True): commande = socket.recv(16) commande = commande.decode() print(commande) socket.send((sys.argv[1] + "\rtoast\n").encode()) if commande == "1": nom = socket.recv(512) nom = nom.decode() c = findContactByNom(lContact, nom) socket.sendto(c) if commande == "2": nom = socket.recv(512) nom = nom.decode() c = findContactByTel(liste, tel) socket.send(c) if commande == "3": nom = socket.recv(512) tel = socket.recv(4) nom = nom.decode() tel = tel.decode()
def PLDsend(self): if self.Dely==1 : if len(self.packetNode[self.watingDelay[0]])<=self.rest and time.time()-self.timedelay>=self.t: self.Send(self.watingDelay[0],self.AckNOW,False,False,False,self.watingDelay[1],'/Del') self.transmitted+=1 self.PLDtotal+=1 self.Delayedtotal+=1 self.notACK.append(self.watingDelay[0]) self.rest-=len(self.packetNode[self.watingDelay[0]]) self.Dely=0 if self.notinOrder==1: self.numOrder+=1 if self.notinOrder==1 : if len(self.packetNode[self.watingorder[0]])<=self.rest and self.numOrder>=self.maxOrder: self.Send(self.watingorder[0],self.AckNOW,False,False,False,self.watingorder[1],'/rord') self.transmitted+=1 self.PLDtotal+=1 self.reordertotal+=1 self.notinOrder=0 self.notACK.append(self.watingorder[0]) self.rest-=len(self.packetNode[self.watingorder[0]]) self.numOrder=0 if self.seq>=len(self.data): return if random.random() < self.pDrop: if len(self.packetNode[self.seq])<=self.rest: self.transmitted+=1 self.PLDtotal+=1 self.droptotal+=1 log.write('{:10s}{:10.2f} {:5s}{:12d}{:12d}{:12d}\n'.format('drop',(time.time()-self.beginTime),'D',self.seq,len(self.packetNode[self.seq]),self.AckNOW)) self.notACK.append(self.seq) self.rest-=len(self.packetNode[self.seq]) self.seq+=self.MSS if self.notinOrder==1: self.numOrder+=1 else: if random.random() < self.pDuplicate: if len(self.packetNode[self.seq])<=self.rest and self.seq-self.MSS in self.packetNode: self.transmitted+=2 self.PLDtotal+=2 self.Duplicatedtotal+=1 # log.write('{:10s}{:10.2f} {:5s}{:12d}{:12d}{:12d}\n'.format('snd',(time.time()-self.beginTime),'D',self.seq,len(self.packetNode[self.seq]),self.AckNOW)) # log.write('{:10s}{:10.2f} {:5s}{:12d}{:12d}{:12d}\n'.format('snd/dup',(time.time()-self.beginTime),'D',self.seq,len(self.packetNode[self.seq]),self.AckNOW)) self.Send(self.seq,self.AckNOW,False,False,False,self.packetNode[self.seq],'') self.Send(self.seq,self.AckNOW,False,False,False,self.packetNode[self.seq],'/dup') self.notACK.append(self.seq) self.rest=self.rest-1*len(self.packetNode[self.seq]) self.seq=self.seq+2*self.MSS if self.notinOrder==1: self.numOrder+=1 else: if random.random() < self.pCorrupt: if len(self.packetNode[self.seq])<=self.rest: self.flagNUM(False,False,False) checksum=self.checksum(self.packetNode[self.seq]) STPpacket = pickle.dumps(PackageSTP(self.seq,self.AckNOW,checksum-1,False,False,False,self.packetNode[self.seq])) if self.notinOrder==1: self.numOrder+=1 self.transmitted+=1 self.PLDtotal+=1 self.corrupttotal+=1 socket.sendto(STPpacket, (self.receiver_host_ip, self.receiver_port)) log.write('{:10s}{:10.2f} {:5s}{:12d}{:12d}{:12d}\n'.format('snd/corr',(time.time()-self.beginTime),'D',self.seq,len(self.packetNode[self.seq]),self.AckNOW)) self.notACK.append(self.seq) self.rest-=len(self.packetNode[self.seq]) self.seq+=self.MSS else: if random.random() < self.pOrder and self.notinOrder==0 and self.Dely==0: if len(self.packetNode[self.seq])<=self.rest: self.notinOrder=1 if (len(self.key)-self.key.index(self.seq)-1)<self.maxOrder: self.maxOrder=len(self.key)-self.key.index(self.seq)-1 self.watingorder=(self.seq,self.packetNode[self.seq]) self.seq+=self.MSS else: if random.random() < self.pDelay and self.notinOrder==0 and self.Dely==0: if len(self.packetNode[self.seq])<=self.rest: self.t=random.randint(0,self.maxDelay)/1000 self.timedelay=time.time() self.watingDelay=(self.seq,self.packetNode[self.seq]) self.Dely=1 self.seq+=self.MSS else: if len(self.packetNode[self.seq])<=self.rest: self.transmitted+=1 self.PLDtotal+=1 self.Send(self.seq,self.AckNOW,False,False,False,self.packetNode[self.seq],'') if self.notinOrder==1: self.numOrder+=1 self.notACK.append(self.seq) self.rest-=len(self.packetNode[self.seq]) self.seq+=self.MSS return
def sendpacket(self,sequence, acknowledge, syn, ack, fin, data): self.flagNUM(syn,ack,fin) STPpacket = pickle.dumps(PackageSTP(sequence, acknowledge,0, syn, ack, fin, data)) self.transmitted+=1 socket.sendto(STPpacket, (self.receiver_host_ip, self.receiver_port)) log.write('{:10s}{:10.2f} {:5s}{:12d}{:12d}{:12d}\n'.format('snd',(time.time()-self.beginTime),self.Flag,sequence,len(data),acknowledge))
from socket import socket, AF_INET, SOCK_DGRAM, timeout socket = socket(AF_INET, SOCK_DGRAM) socket.settimeout(1) socket.sendto(b"zad14odp;src;60788;dst;2901;data;programming in python is fun", ("localhost", 2019)) print(socket.recv(1024)) socket.sendto(b"zad14odp;src;60788;dst;2901;data;programmig in python is fun", ("localhost", 2019)) print(socket.recv(1024)) socket.sendto(b"zad14odp;src;60788;dst;2901;dta;programming in python is fun", ("localhost", 2019)) print(socket.recv(1024))
clients = {'player1': None, 'player2': None} PORT_NUMBER = 5009 SIZE = 4096 hostName = gethostbyname(gethostname()) socket = socket(AF_INET, SOCK_DGRAM) socket.bind((hostName, PORT_NUMBER)) print("Test server listening on port %s\n at %s\n\n" % (str(PORT_NUMBER), str(gethostbyname(gethostname())))) while True: incoming = socket.recvfrom(SIZE) (data, addr) = incoming if pickle.loads(data) == '': if clients.get('player2', None) == None: if clients.get('player1', None) != None: clients['player2'] = addr print('Player 2 Connected') else: clients['player1'] = addr print('Player 1 Connected') if incoming[1] == clients['player1']: if clients['player2'] != None: socket.sendto(data, clients['player2']) if incoming[1] == clients['player2']: if clients['player1'] != None: socket.sendto(data, clients['player1']) sys.exit()
from socket import socket, AF_INET, SOCK_DGRAM socket = socket(family=AF_INET, type=SOCK_DGRAM) socket.bind(("localhost", 8003)) while True: info = input("输入信息:") socket.sendto(info.encode("utf-8"), ("localhost", 8002))