Python套接字监听器保持低调

时间:2015-02-04 10:24:30

标签: python sockets

我有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检查是否有效。

1 个答案:

答案 0 :(得分:1)

错误是正常的:

  • 你听一个队列大小为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