Search code examples
pythonsocketstcpudpclient

Python socket always close


I have a socket client which uses TCP and UDP sockets, even I don't close the socket connection, however, when I finished the execution of the script, the connection is disconnected How can I keep the connection always ON,
This is the code:

import socket
import sys
import time

HOST = "163.173.96.12"  # Standard loopback interface address (localhost)
PORT = 32000        # Port to listen on TCP/IP
PORT1 = 32001       # Port to listen on UDP/IP

#TCP/IP
try:
    client_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_address = (HOST, PORT)
except:
    print("Cannot find server TCP")
finally:
    client_tcp.connect(tcp_server_address)
    print('Connection TCP sucessful')

#UDP/IP
try:
    client_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    udp_server_address = (HOST, PORT1)
except:
    print("Cannot find server UDP")
finally:
    client_udp.connect(udp_server_address)
    print('Connection UDP sucessful')

try:
    for i in range(1,11):
        texte = "PING\n"
        client_tcp.send(texte.encode())
        data=client_tcp.recv(1024).decode('utf-8')
        print("Received ", str(data))
except:
    print("error occur")    
finally: 
    #client_tcp.close()
    #client_udp.close()
    print('Closed')

Thanks


Solution

  • The socket is closes because when you reach the end of the program the process die then the operating system see resources (socket) that are unused by a process, so it removes them.

    To prevent this, you need to prevent the process from dying. So add one of these at the end of the program, and it will not close, keeping the socket open :

    input("Press enter to close")
    
    from threading import Event
    
    Event().wait()