Python插座总是关闭
我有一个使用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')
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
插座已关闭,因为当您到达程序的末尾时,进程死亡,然后操作系统会查看未经过程未使用的资源(套接字),因此它可以将其删除。
为了防止这种情况,您需要防止该过程死亡。
因此,在程序结束时添加其中一个,并且不会关闭,保持插座打开:
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 :