def start_sending(delay, perdida): print 'perdida: ', perdida, ' - delay: ', delay times = [] print "Vas a mandar paquetes de tamano: ", SIZES received = str() with Socket(delay, perdida) as sock2: sock2.connect(CONNECTION_DIR) for size_to_send in SIZES: # si no es un size valido salgo if size_to_send == NULL_SIZE: break for i in range(REPEAT_SEND): # espero a q el server me diga cuando empezar a mandar sock2.recv(MAX_BUFFER) # si el server nos contesto, significa que ya le podemos empezar a enviar. to_send = "a" * size_to_send # empiezo a mandar print "Envio ", size_to_send, ' bytes ( iteracion ', i, ')' sock2.send(to_send) # Cerramos el stream de escritura pero podemos seguir recibiendo datos. sock2.shutdown(SHUT_WR) sock2.close()
def main(server_ip, size): with Socket() as sock: print '[client] Connecting...' sock.connect((server_ip, 6677)) print '[client] Connection established.' print '[client] Sending file size...' sock.send(pack('I', size)) print '[client] Uploading %d bytes...' % size t0 = time() sock.send('a' * size) sock.shutdown(SHUT_WR) # Cerramos el stream de escritura pero podemos seguir recibiendo datos. t1 = time() t = t1 - t0 print '[client] Upload time: %f seconds' % t print '[client] Connection closed.'
def main(ack_delay, ack_loss_probability): with Socket(ack_delay=ack_delay, ack_loss_probability=ack_loss_probability) as sock: sock.bind(('0.0.0.0', 6677)) sock.listen() print '[PTC server] Waiting for a client...' sock.accept() print '[PTC server] Connection established.' size = unpack('I', sock.recv(4))[0] print '[PTC server] Receiving %d bytes...' % size received = str() while len(received) < size: received += sock.recv(size - len(received)) print '[PTC server] Received %d bytes.' % len(received) sock.close() print '[PTC server] Received %d bytes. Connection closed.' % size
def run(self): to_send = open(self.outgoing_filename).read() expected_size = len(open(self.incoming_filename).read()) with Socket() as sock: # La conexión del socket queda definida por cada subclase. # El cliente se conecta activamente mientras que el servidor se # ligará a una dirección determinada y escuchará allí. self._connect_socket(sock) i = 0 # Para recibir el archivo, iterar hasta que el tamaño deseado # queda totalmente cubierto. while len(self.received_bytes) < expected_size: # Siendo PTC un protocolo full-duplex, al mismo tiempo también # podemos mandar datos a nuestro interlocutor. sock.send(to_send[i:i+self.CHUNK_SIZE]) chunk = sock.recv(self.CHUNK_SIZE) self.received_bytes += chunk i += self.CHUNK_SIZE # Por último, enviar todos los bytes remanentes. if i < len(to_send): sock.send(to_send[i:]) self._write_file()
def start_server(delay, perdida): tiempo = {} print 'perdida: ', perdida, ' - delay: ', delay print "Vas a recibir paquetes de tamano: ", SIZES with Socket(delay, perdida) as sock1: sock1.bind(CONNECTION_DIR) sock1.listen() sock1.accept() for size_to_recv in SIZES: # chequeo que es un tamano valido if size_to_recv == NULL_SIZE: break for i in range(REPEAT_SEND): sock1.send(SERVER_MSG_OK) # le aviso de que empiece a mandar print '\nComienzo a recibir ', size_to_recv, ' bytes ( iteracion ', i, ')' startTime = time.time() str_recv = "" while (size_to_recv > len(str_recv)): str_recv += sock1.recv(MAX_BUFFER) totalTime = time.time() - startTime if not tiempo.has_key(size_to_recv): tiempo[size_to_recv] = [] tiempo[size_to_recv].append(totalTime) print '\tRecibidos los %d bytes' % (size_to_recv) print '\tTiempo = %.10f' % (totalTime) sock1.close() save_result( FILE_FMT % ('server', str(delay), str(perdida), len(SIZES), MAX_BUFFER), delay, perdida, tiempo)
timer = threading.Timer(0.01, change_drop) timer.start() #timer = threading.Timer(0.01, change_delay) #timer.start() timer = threading.Timer(0.01, change_drop) timer.start() protocol.ACK_delay = 0 #ACKs = [0.01, 0.02, 0.03, 0.04, 0.05] ACKs = [0.075, 0.1] tests = [] with Socket() as sock2: sock2.connect((sys.argv[1], 6677)) for i in l: #print "\nRunning file: " + str(len(i)/1024) + "kb" for k in range(0, len(ACKs)): h = Info() h.runsCount = 3 h.delay = ACKs[k] protocol.ACK_delay = h.delay #print "Using delay: " + str(protocol.ACK_delay) protocol.droppedPackets = 0 for j in range(0, h.runsCount): sock2.send(tp_protocol.SEND) data = sock2.recv(10) if data == tp_protocol.OK: #print "mando longitud de mensaje: " + str(len(i))
parser = argparse.ArgumentParser() parser.add_argument('--host', help='Server hostname') parser.add_argument('-a', '--alpha', type=int, help='Start Alpha') parser.add_argument('-b', '--beta', type=int, help='Start Beta') parser.add_argument('-p', '--port', type=int, help='Server port') parser.add_argument('-s', '--size', type=int, help='Bytes to send') parser.add_argument('--fpath') args = parser.parse_args() alphaStart = args.alpha betaStart = args.beta for alpha in range(alphaStart, 11, 1): for beta in range(betaStart, 12, 1): filepath = args.fpath with Socket(beta=beta / 10.0, alpha=alpha / 10.0, k=4, filepath=filepath) as sock: print 'Connecting...' print gethostbyname(args.host) print args.port sock.connect((gethostbyname(args.host), args.port), timeout=10) print 'Connection established.' print 'Sending file size...' sock.send(pack('I', args.size)) #da la representacion en bytes de size print 'Uploading %d bytes...' % args.size sock.send('a' * args.size) #crea un string con 50 a's sock.shutdown(SHUT_WR) time.sleep(1) betaStart = 0 print 'Connection closed.'
import argparse from ptc import Socket, SHUT_WR from socket import gethostbyname from struct import pack parser = argparse.ArgumentParser() parser.add_argument('--host', help='Server hostname') parser.add_argument('-p', '--port', type=int, help='Server port') parser.add_argument('-s', '--size', type=int, help='Bytes to send') parser.add_argument('-a', '--alpha', type=float, help='Alpha', default=0.125) parser.add_argument('-b', '--beta', type=float, help='Beta', default=0.25) parser.add_argument('-k', '--kvar', type=float, help='K', default=4) parser.add_argument('--fpath') args = parser.parse_args() with Socket(beta=args.beta, alpha=args.alpha, k=args.kvar, filepath = args.fpath) as sock: print 'Connecting...' print gethostbyname(args.host) print args.port sock.connect((gethostbyname(args.host), args.port), timeout=10) print 'Connection established.' print 'Sending file size...' sock.send(pack('I', args.size)) #da la representacion en bytes de size print 'Uploading %d bytes...' % args.size sock.send('a' * args.size) #crea un string con 50 a's sock.shutdown(SHUT_WR) print 'Connection closed.'
import time from ptc import Socket, SHUT_WR from socket import gethostbyname from struct import pack parser = argparse.ArgumentParser() parser.add_argument('--host', help='Server hostname') parser.add_argument('-a', '--alpha', type=float, help='Start Alpha') parser.add_argument('-b', '--beta', type=float, help='Start Beta') parser.add_argument('-p', '--port', type=int, help='Server port') parser.add_argument('-s', '--size', type=int, help='Bytes to send') parser.add_argument('--fpath') args = parser.parse_args() alpha = args.alpha beta = args.beta filepath = args.fpath with Socket(beta=beta, alpha=alpha, k=4, filepath=filepath) as sock: print 'Connecting...' print gethostbyname(args.host) print args.port sock.connect((gethostbyname(args.host), args.port), timeout=10) print 'Connection established.' print 'Sending file size...' sock.send(pack('I', args.size)) #da la representacion en bytes de size print 'Uploading %d bytes...' % args.size sock.send('a' * args.size) #crea un string con 50 a's sock.shutdown(SHUT_WR) print 'Connection closed.'
parser = argparse.ArgumentParser() parser.add_argument('--host', help='Server hostname') parser.add_argument('-a', '--alpha', type=int, help='Start Alpha') parser.add_argument('-b', '--beta', type=int, help='Start Beta') parser.add_argument('-p', '--port', type=int, help='Server port') parser.add_argument('-l', '--loss', type=float, default=0.0, help='probability of losing a packet (default 0)') parser.add_argument('-s', '--size', type=int, help='Bytes to send') parser.add_argument('--fpath') args = parser.parse_args() alphaStart = args.alpha betaStart = args.beta for alpha in range(alphaStart,11,1): for beta in range(betaStart,11,1): filepath = args.fpath with Socket(beta=beta/10.0, alpha=alpha/10.0, k=4, filepath = filepath, packet_loss_probability=args.loss) as sock: print 'Connecting...' print gethostbyname(args.host) print args.port sock.connect((gethostbyname(args.host), args.port), timeout=10) print 'Connection established.' print 'Sending file size...' sock.send(pack('I', args.size)) #da la representacion en bytes de size print 'Uploading %d bytes...' % args.size sock.send('a' * args.size) #crea un string con 50 a's sock.shutdown(SHUT_WR) time.sleep(1) betaStart = 0 print 'Connection closed.'
from ptc import Socket, SHUT_WR except: import sys sys.path.append('../../') from ptc import Socket, SHUT_WR SERVER_IP = '127.0.0.1' SERVER_PORT = 6677 to_send = 'foo bar baz' received = str() # Usar sockets PTC dentro de bloques with. Esto nos asegura que los recursos # subyacentes serán liberados de forma adecuada una vez que el socket ya no # se necesite. with Socket() as client_sock: # Establecer una conexión al PTC corriendo en el puerto SERVER_PORT en # el host con dirección SERVER_IP. Esta llamada es bloqueante, aunque # en este caso se declara un timeout de 10 segundos. Pasado este tiempo, # el protocolo se dará por vencido y la conexión no se establecerá. client_sock.connect((SERVER_IP, SERVER_PORT), timeout=10) # Una vez aquí, la conexión queda establecida exitosamente. Podemos enviar # y recibir datos arbitrarios. client_sock.send(to_send) received += client_sock.recv(10) # Cerramos nuestro stream de escritura pero podemos continuar recibiendo # datos de la contraparte. client_sock.shutdown(SHUT_WR) received += client_sock.recv(20) print 'client_sock received: %s' % received
type=float, default=0.0, help='ACK packet delay in seconds (default 0)') #Agrego el parametro de perdida de ACK parser.add_argument('-l', '--loss', type=float, default=0.0, help='probability of losing an ACK packet (default 0)') #Agrego el parametro de puerto parser.add_argument('-p', '--port', type=int, default=6677, help='PTC port') args = parser.parse_args() for alpha in range(0, 10, 1): for beta in range(0, 10, 1): with Socket(ack_delay=args.delay, ack_loss_probability=args.loss) as sock: sock.bind(('127.0.0.1', args.port)) sock.listen() print 'Waiting for a client...' sock.accept() print 'Connection established.' size = unpack('I', sock.recv(4))[0] print 'Receiving %d bytes...' % size received = str() #Un while que solo reciba los datos y los lea del buffer #Guarda los datos recibidos en received (print para verlo) while len(received) < size: received += sock.recv(size - len(received)) print 'Received %d bytes.' % len(received) sock.close()
try: from ptc import Socket except: import sys sys.path.append('../../') from ptc import Socket SERVER_IP = '127.0.0.1' SERVER_PORT = 6677 to_send = 'Lorem ipsum dolor sit amet' received = str() # Usar sockets PTC dentro de bloques with. Esto nos asegura que los recursos # subyacentes serán liberados de forma adecuada una vez que el socket ya no # se necesite. with Socket() as server_sock: # Ligar el socket a una interfaz local a través de la tupla (IP, PORT). server_sock.bind((SERVER_IP, SERVER_PORT)) # Pasar al estado LISTEN. server_sock.listen() # Esta llamada se bloqueará hasta que otro PTC intente conectarse. No # obstante, luego de diez segundos de no recibir conexiones, PTC se # dará por vencido. server_sock.accept(timeout=10) # Una vez aquí, la conexión queda establecida exitosamente. Podemos enviar # y recibir datos arbitrarios. received += server_sock.recv(15) server_sock.send(to_send) print 'server_sock received: %s' % received
if len(sys.argv) >= 3: protocol.ACK_chance = float(sys.argv[2]) #protocol.droppedPackets = 0 stopTimer = False def change_delay(): protocol.ACK_delay = random.random() * 0.13 + 0.02 global stopTimer if not stopTimer: timer = threading.Timer(0.01, change_delay) timer.start() timer = threading.Timer(0.01, change_delay) #timer.start() with Socket() as sock1: print "Server running on: " + get_lan_ip() sock1.bind((get_lan_ip(), 6677)) sock1.listen() sock1.accept() while True: data = sock1.recv(10) #print "recibi algo: " + data if data == tp_protocol.SEND: #print "mando ok: " sock1.send(tp_protocol.OK) numBytes = int(sock1.recv(10)) #print "recibi numBytes: " + str(numBytes) #print "mando ok: " sock1.send(tp_protocol.OK)