Python 套接字总是关闭
Python socket always close
我有一个使用TCP和UDP套接字的套接字客户端,即使我没有关闭套接字连接,但是当我执行完脚本时,连接断开了
我怎样才能保持连接始终打开,
这是代码:
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')
谢谢
套接字已关闭,因为当您到达程序末尾时,进程终止,然后操作系统看到进程未使用的资源(套接字),因此将其删除。
要防止这种情况,您需要防止进程死亡。
所以在程序末尾添加其中之一,它不会关闭,保持套接字打开:
input("Press enter to close")
from threading import Event
Event().wait()
我有一个使用TCP和UDP套接字的套接字客户端,即使我没有关闭套接字连接,但是当我执行完脚本时,连接断开了
我怎样才能保持连接始终打开,
这是代码:
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')
谢谢
套接字已关闭,因为当您到达程序末尾时,进程终止,然后操作系统看到进程未使用的资源(套接字),因此将其删除。
要防止这种情况,您需要防止进程死亡。 所以在程序末尾添加其中之一,它不会关闭,保持套接字打开:
input("Press enter to close")
from threading import Event
Event().wait()