Posterior a investigar en diversos repositorios y sitios webs al final encontramos la respuesta que te compartimos aquí.
Ejemplo 1: cerrar conexión socket python
### Answer to: "close connection socket python" ###
sock.close();
sock.shutdown(socket.SHUT_RDWR);#### sock.close():# Decrements the handle count by one and if the handle count has reached zero# then the socket and associated connection goes through the normal close# procedure (effectively sending a FIN / EOF to the peer) and the socket is# deallocated.# # Docs: https://docs.python.org/3/library/socket.html#socket.close# Close a socket file descriptor. This is like os.close(), but for sockets.# On some platforms (most noticeable Windows) os.close() does not work for# socket file descriptors.# # # sock.shutdown(socket.SHUT_RDWR):# For reading and writing closes the underlying connection and sends a FIN /# EOF to the peer regardless of how many processes have handles to the socket.# However, it does not deallocate the socket and you still need to call close# afterward.# # # Docs: https://docs.python.org/3/library/socket.html#socket.socket.shutdown# Shut down one or both halves of the connection. If how is SHUT_RD, further# receives are disallowed. If how is SHUT_WR, further sends are disallowed.# If how is SHUT_RDWR, further sends and receives are disallowed.###
Ejemplo 2: desconexión del socket de Python
import select
import socket
ip ='127.0.0.1'
port =80
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect((ip, port))whileTrue:try:
ready_to_read, ready_to_write, in_error =
select.select([conn,],[conn,],[],5)except select.error:
conn.shutdown(2)# 0 = done receiving, 1 = done sending, 2 = both
conn.close()# connection error event here, maybe reconnectprint('connection error')breakiflen(ready_to_read)>0:
recv = conn.recv(2048)# do stuff with received dataprint(f'received: recv')iflen(ready_to_write)>0:# connection established, send some stuff
conn.send('some stuff')
Si aceptas, tienes la libertad de dejar un ensayo acerca de qué te ha gustado de este ensayo.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)