What I want to do
I would like to use again sTCP.connect() with a different IP and PORT
My problem
In the next interaction of while (when I have a different IP and PORT than the last one), I get an Error: "This connection is already in use" What can I do in order to make it work? The socket is declared before the while loop. For clearance I'll only show the while loop:
while y != numero_de_lineas:
print "Interaccion numero", y
if reintentar == 1:
print y
reintentar = 0
tupla = (str(iplista[y]),int(portlista[y]))
sUDP.sendto(mensaje1,tupla)
try:
if reintentar != 1: #si estoy reintentando no quiero otro timeout
sUDP.settimeout(time_out)
respuesta1 , address1 = sUDP.recvfrom(BUFFER_SIZE)
#si todo va bien tengo respuesta1
#print(respuesta1) #recibo ni ok ni no
if (respuesta1 == "ok") or (reintentar != 1):
sTCP.connect((iplista[y],int(portlista[y]))) #SE CONECTA N VECES, HAY QUE ACCEPTAR OTRA CONEXION CON .accept()
contenido_fichero = fichero.read() #lo que hay dentro de ./fichero.txt
sTCP.send(contenido_fichero)
try:
sTCP.settimeout(time_out_TCP) #esperamos 10 segundos
respuesta2 = sTCP.recv(BUFFER_SIZE)
#LIBERAMOS LA CONEXION TCP
#print(respuesta2) #recibo transferdone
#si recibe respuesta1 y respuesta2 paramos
#empezamos con el calculo de la huella con el server aceptado iplista[y],portlista[y]
huella_md5 = md5.new() #creamos la huella
huella_md5.update(contenido_fichero) #actualicamos su contenido (le podemos meter mas strings despues)
huella_md5_calculada = huella_md5.hexdigest() #huella en string
sUDP.sendto(huella_md5_calculada,tupla)
try:
sUDP.settimeout(time_out_TCP) #porque son 10 segundos
respuesta3 , address3 = sUDP.recvfrom(BUFFER_SIZE)
if respuesta3 == "md5sum ok":
print "Copia de fichero en servidor",iplista[y],"correcta"
if respuesta3 == "md5sum error":
print "Error en la copia del fichero en el servidor",iplista[y],"Se vuelve a intentar" #REINTENTAR
reintentar = 1
except socket.timeout:
print "Error en la copia del fichero en el servidor",iplista[y],". Finalizado el intento"
except socket.timeout:
print "Error en la transferencia con el servidor",str(iplista[y])
if respuesta1 == "no":
print "Error. El servidor",iplista[y],"no acepta el fichero"
except socket.timeout:
print "Error: no hay respuesta por parte del servidor", iplista[y] , "en el puerto", portlista[y]
#if y == (numero_de_lineas-1): #-1 porque para y el cero cuenta
#sys.exit() #si todos fallaron al conectar udp nos salimos
Edit:
This is the socket declaration (it is located before the while loop)
try: #tenemos que crear el socket tcp en cada interaccion porque sino ya esta en uso
sUDP = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #UDP
sTCP = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #TCP
except socket.error :
print "Error al crear socket TCP"
sys.exit()