Python套接字侦听器

2024-09-28 03:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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侦听器来检查它是否正常工作。在


Tags: 项目端口代码importnone应用程序returnport
1条回答
网友
1楼 · 发布于 2024-09-28 03:17:59

错误正常:

  • 您收听的是队列大小为5的套接字
  • 你从不接受任何联系

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

您必须接受从侦听队列中删除它的请求并使用它(来自相关post的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

相关问题 更多 >

    热门问题