gpt4 book ai didi

Python套接字监听器保持关闭

转载 作者:太空宇宙 更新时间:2023-11-03 17:57:13 24 4
gpt4 key购买 nike

我有Python项目。该项目正在监听端口。这是我的代码:

import socket

conn = None # socket connection

###
# port listener
# @return nothing
###
def listenPort():
global conn
conn = socket.socket()
conn.bind(("", 5555))
conn.listen(5)

运行我的应用程序后,我检查了 hercules用于端口连接。它有效,但我断开连接并再次连接。执行此操作后5次连接返回错误。我希望听众必须始终工作。我怎样才能得到我想要的应用程序?提前致谢!

编辑

我将仅在服务器上运行我的应用程序,并且我将通过Uptime root进行检查监听器正在工作。

最佳答案

该错误是正常的:

  • 您监听队列大小为 5 的套接字
  • 您从不接受任何连接

=> 您将 5 个连接请求排入队列,第 6 个连接请求导致错误。

您必须接受请求才能将其从监听队列中删除并使用它(从相关帖子派生的命令accepter = conn.accept())

编辑

这是一个功能齐全的示例:

def listenPort():
global conn
conn = socket.socket()
conn.bind(("", 5555))
conn.listen(5)
while True:
s, addr = conn.accept() # you must accept the connection request
print("Connection from ", addr)
while True: # loop until othe side shuts down or close the connection
data = s.recv(17) # do whatever you want with the data
# print(data)
if not data: # stop if connection is shut down or closed
break
# for example stop listening where reading keyword "QUIT" at begin of a packet
# elif data.decode().upper().startswith("QUIT"):
# s.close()
# conn.close()
# return
s.close() # close server side

关于Python套接字监听器保持关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28318946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com