2

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()
1
  • @PatrickArtner here you have Commented Dec 17, 2017 at 10:30

2 Answers 2

2

You cannot connect twice on the same socket instance. You have to create a new socket object each time, i.e. you need

sTCP = socket.socket(...)

each time before you call .connect(...).

Don't forget to .close() and/or .shutdown() the old socket instance.

Sign up to request clarification or add additional context in comments.

4 Comments

So lets suppose I declare sTCP in the loop and I do .connect() in the loop.... Do I have to put sTCP.close() or sTCP.shutdown() at the end of the loop in order to make it work in the next interaction of the while? @freakish
@GinésDíaz: you don't have to close the socket, but you should to ensure that resources are properly released, just as you would a file.
@mhawke so thats my question, how can I release the TCP connection to use it again with a different IP?
@GinésDíaz: sorry, strictly speaking you do not have to close the socket, but you should close it with socket.shutdown() and socket.close() because it is good practice to (so both local and remote resources can be released). You can create a new socket and bind it to the same variable, in which case the original socket object should become eligible for garbage collection, and eventually cleaned up - but that's unpredictable and the remote peer might not be informed that it's connection is lost.
1

I don't think that you are using a different destination (IP, port) pair because y is never changed. The address is given by:

(iplista[y],int(portlista[y]))

So if y never changes the same address will be used. Because the connection is still open from the previous loop, a new connection attempt fails.

Perhaps you should be incrementing y in the loop.

You should also be closing the connection once you are done with it to ensure that resources are properly released. Use sTCP.shutdown() followed by sTCP.close() for that. Then create a new socket for the next connection (N.B. that means that you need to create the socket inside the loop).

1 Comment

Im sorry I forgot to include y = y+1 at the end of the loop , but thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.